Home > database >  Scanf not compiling
Scanf not compiling

Time:09-26

I'm new to C and having a weird issue while compiling below code on Ubunto using gcc.

#include <stdio.h>
int main()
{
    char c;
    printf("Inserire la codifica numerica :");
    scanf(" %d",&c);
    printf("La traduzione é %c\n",c);
    return 0;
}

When I compile the code I get the following error:

$ gcc codbin.c -o codbin.out
codbin.c: In function ‘main’:
codbin.c:7:14: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘char *’ [-Wformat=]
    7 |     scanf(" %d",&c);
      |             ~^  ~~
      |              |  |
      |              |  char *
      |              int *
      |             %hhd

But it should work based on what our professor told us at the university course. Any idea?

Thanks in advance, any help would be really appreciated!

CodePudding user response:

I think the error message is exceptionally clear.

%d expects an int.

But the variable you provided, c, was declared as a char:

char c;

I very much doubt your professor said this was OK, but if they did, they are just completely wrong.

The format string with % identifiers must match the parameters provided.

CodePudding user response:

First of all, that is just a warning, meaning your code should still compile so please check if the file codbin.out exists.

If it does not, you may have a different issue you did not show us.

Second, as already been pointed out, the reason for the warning is that your format specifier "%d" does not match the variable type char.

"%d" expects you to provide pointer to int variable.

What you haven't been told, is that your program could still work, but it will be a fluke.

Because char is smaller than int, scanf may try to write to memory it is not suppose to use. This is called "undefined behavior" which means it can change depending on what compiler you use, what OS you run on, and what state your computer is in when you run the program.

Your program could crash, print something weird, or work as if it is fine, even though the code is wrong.

  • Related