문제

My task is to create array, In order to do that I need to input size, but I have to make sure that the input isn't negative, letter or symbol. I created function to do that, but my if doesn't work properly. If I enter negative number or character it still uses it.

Here's the function which I use:

void getsize(int* size){
    printf("Enter the size of array\n");
  if ((scanf("%d", size) == 1) && (getchar() == '\n') && (size > 0)){
     printf("Size: %d entered\n", *size);
  } else {
   printf("wrong input\n");
   while(getchar() != '\n');
  }
}

getsize(&size);
도움이 되었습니까?

해결책

The main problem is, you compare the address of the value to 0. size is a pointer, so use:

 (*size > 0)

instead of

 (size > 0)

다른 팁

You are comparing the pointer with the 0, not the value you've stored inside the memory location it points to. Inside your if, rather use the following as your final comparison:

... (*size > 0)) { ... }

in your if statement. you are checking for size > 0 This should be *size > 0

void getsize(int* size){
    printf("Enter the size of array\n");
    if ((scanf_s("%d", size) == 1) && (getchar() == '\n') && (*size > 0)){
        printf("Size: %d entered\n", *size);
    }
    else {
        printf("wrong input\n");
        while (getchar() != '\n');
    }
}

This works for me. Just change size>0 to *size>0, because you must check the value, not the address.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top