Why does scanf ("% hhu", char *) overwrite other variables when they are local?

The title says it all. I am using GCC 4.7.1 (bundled with CodeBlocks) and I am having a weird problem. Consider this:

int main() { unsigned char a = 0, b = 0, c = 0; scanf("%hhu", &a); printf("a = %hhu, b = %hhu, c = %hhu\n", a, b, c); scanf("%hhu", &b); printf("a = %hhu, b = %hhu, c = %hhu\n", a, b, c); scanf("%hhu", &c); printf("a = %hhu, b = %hhu, c = %hhu\n", a, b, c); return 0; } 

For inputs 1, 2, and 3, these outputs

 a = 1, b = 0, c = 0 a = 0, b = 2, c = 0 a = 0, b = 0, c = 3 

If I, however, declare a, b, and c global variables, it works as expected. Why is this happening?

Thank you in advance

Other information:

I have a 64-bit version of Windows 8. I also tried with -std = c99 and the problem persists.

Further research

Testing this code

 void printArray(unsigned char *a, int n) { while(n--) printf("%hhu ", *(a++)); printf("\n"); } int main() { unsigned char array[8]; memset(array, 255, 8); printArray(array, 8); scanf("%hhu", array); printArray(array, 8); return 0; } 

shows that scanf interprets "% hhu" as "% u". He directly ignores "hh". Output code code with input 1:

 255 255 255 255 255 255 255 255 1 0 0 0 255 255 255 255 
+4
source share
1 answer

An important detail is that you are using Windows and the supposedly outdated or inappropriate C environment (compiler and standard library). MSVCRT only supports C89 (and even then, not quite right); in particular, C89 did not have an โ€œhhโ€ modifier, and it probably interpreted โ€œhhโ€ in the same way as โ€œhโ€ (i.e. short ).

+7
source

All Articles