Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

c - Why is scanf("%hhu", char*) overwriting other variables when they are local?

The title says it all. I'm using GCC 4.7.1 (bundled with CodeBlocks) and I faced a strange issue. Consider this:

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

For inputs 1, 2 and 3, this 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 as global variables, it works as expected. Why is this happenning?

Thank you in advance

Other details:

I'm running Windows 8 64 bits. 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("
");
}

int main() {
    unsigned char array[8];
    memset(array, 255, 8);
    printArray(array, 8);
    scanf("%hhu", array);
    printArray(array, 8);
    return 0;
}

shows that scanf is interpreting "%hhu" as "%u". It is directly ignoring the "hh". The output of the code with input 1 is:

255 255 255 255 255 255 255 255
1 0 0 0 255 255 255 255
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The important detail is that you're using Windows, and presumably an outdated or non-conforming C environment (compiler and standard library). MSVCRT only supports C89 (and even then, not entirely correctly); in particular, there was no "hh" modifier in C89, and it's probably interpreting "hh" the same as "h" (i.e. short).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...