strange behavior of scanf for short int

后端 未结 5 2033
余生分开走
余生分开走 2020-12-11 10:25

the code is as follows:

#include 
main()
{
    int m=123;
    int n = 1234;
    short int a;
    a=~0;
          


        
5条回答
  •  盖世英雄少女心
    2020-12-11 11:10

    Assuming that int and short are four- and two-byte integers, respectively, on your platform (which is a likely assumption, but not guaranteed by the standard), you're asking scanf to read in an integer and store it in four bytes: the two bytes of b, and whatever two bytes follow it in memory. (Well, technically this is undefined behavior, and no specific behavior is guaranteed; but that's what it's likely to do.) Apparently your compiler is using the two bytes after b as the first two bytes of m. Which is a bit surprising — I certainly wouldn't expect b and m to be adjacent, and it rather implies that your compiler isn't aligning shorts and ints to the beginning of four-byte blocks — but perfectly legal.

    You can see better what's going on if you add

    printf("&a: %08X\n&m: %08X\n", (int)&a, (int)&m);
    

    which will show you where a and m are stored, relative to each other. (Just as a test, I mean. You wouldn't want that in "real" code.)

提交回复
热议问题