Search code examples
cscanfgetchar

Using scanf on integer


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);

Solution

  • 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)