为什么我的工会的规模比我预期的要大? [英] Why is my union's size bigger than I expected?
问题描述
当我像这样打印联合的大小时:
When I print the size of a union like this:
union u {
char c[5];
int i;
} un;
使用此:
int _tmain(int argc, _TCHAR* argv[])
{
printf("size of union = %d ",sizeof(un));
return 0;
}
使用Visual C ++得到的答案是8,但是我希望是5.为什么?
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("\n un.c[0] = %x ",un.c[0]);
printf("\n un.c[1] = %x ",un.c[1]);
printf("\n un.c[2]= %x ",un.c[2]);
printf("\n un.c[3] = %x ",un.c[3]);
printf("\n un.c[4] = %x ",un.c[4]);
printf("size of union = %d ",sizeof(un));
我得到了类似
un.c[0] = 34;
un.c[1] = 12;
un.c[2] = 76;
un.c[3] = ffffff98;
为什么在un.c [3]处有6fs
why are there 6fs at un.c[3]
推荐答案
sizeof
运算符产生变量或类型的大小,包括分隔元素所需的任何填充该类型的数组中的所有内容仍正确对齐.由于您的联合具有 int
成员,因此需要4字节对齐,因此其自然"大小将向上舍入为4字节的下一个倍数.
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.
ffffff98
是因为您正在使用带符号的 char
进行编译.将%x
与不是 unsigned int
的参数一起使用会导致未定义的行为;您所看到的有时称为 sign-extension .别名的结果是 0x98
重新解释为 char
,即 -104
.在升级为 int
(称为默认参数提升)和保留为 -int的int
变为 -104
时,它保留了其价值.> unsigned int 0xffffff98
.
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
.
这篇关于为什么我的工会的规模比我预期的要大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!