Reading small int with scanf

2019-02-28 12:38发布

问题:

Is there a way to read a small int (i.e. 1-byte int of range -128..127) using scanf? Consider this code:

char x;
scanf("%d", &x);

The program will read an int, most probably 4 bytes, and try to write it at the address of x, thus violating the 3 bytes which come in the memory after this address.

I know there is a modifier for short int (%h), but I haven't heard about one for small int (char) ?

回答1:

scanf needs "%hhd" format string to read into a char.



标签: c scanf