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

Categories

When I print the size of a union like this:

union u {
  char c[5];
  int i;
} un;

using this:

int _tmain(int argc, _TCHAR* argv[])
{
    printf("size of union = %d ",sizeof(un));
    return 0;
}

I get an answer of 8 using Visual C++, but I expected 5. Why?

Well, for the same example, i did something like this:

int i1 = 0x98761234;
un.i = i1;
printf("
 un.c[0] = %x ",un.c[0]);
printf("
 un.c[1] = %x ",un.c[1]);
printf("
 un.c[2]= %x ",un.c[2]);
printf("
 un.c[3] = %x ",un.c[3]);
printf("
 un.c[4] = %x ",un.c[4]);
printf("size of union = %d ",sizeof(un));

i got results like

un.c[0] = 34;
un.c[1] = 12;
un.c[2] = 76;
un.c[3] = ffffff98;

why are there 6fs at un.c[3]

See Question&Answers more detail:os

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

1 Answer

The sizeof operator produces the size of a variable or type, including any padding necessary to separate elements in an array of that type such that everything is still correctly aligned. Since your union has an int member, it needs to be 4-byte aligned, so its "natural" size gets rounded upwards to the next multiple of 4 bytes.


The ffffff98 is because you're compiling with signed char. Using %x with an argument that is not unsigned int causes undefined behaviour; what you're seeing is sometimes called sign-extension. The result of your aliasing is 0x98 reinterpreted as char, which is -104. This retains its value on being promoted to int (this is called the default argument promotions), and the int -104 when aliased as unsigned int becomes 0xffffff98.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...