I wanted to make a little experiment with scanf(). I wanted to read a small (<=255) integer from the user and store it in a char type.
I did:
char ch;
scanf("%d",&ch);
It works, but I want to satisfy the compiler and not to get this warning:
warning: format specifies type 'int *'
but the argument has type 'char *' [-Wformat]
scanf("%d",&ch);
Any idea?
CodePudding user response:
First of all, to store a value 0 - 255, you should never use char
. In fact you should never use char
for the intention of storing anything but characters and strings. This is because that type has implementation-defined signedness: Is char signed or unsigned by default?
You could do:
unsigned char val;
scanf("%hhu", &val);
Although it is often best practice to use the portable types from stdint.h
:
#include <stdint.h>
#include <inttypes.h> // (actually includes stdint.h internally)
uint8_t val;
scanf("%"SCNu8, &val);
CodePudding user response:
The warning message you are seeing is indicating that the scanf() function is expecting an int * (a pointer to an integer) as the second argument, but you are providing a char * (a pointer to a character) instead.
To avoid the warning message and ensure that the program works correctly, you should use the correct format specifier for a char variable in the scanf() function.
For example, you can use the %c format specifier to read a single character from the user and store it in a char variable:
char ch;
scanf(" %c", &ch);