简体   繁体   English

C ++结构中的奇怪行为

[英]Strange behavior in C++ struct

I know that Union members share memory space, so I expect following code to output 9 & 9. However, I get 12 & 9. Why? 我知道联盟成员共享内存空间,因此我希望以下代码输出9和9。但是,我得到12和9。为什么?

union Sample_union {
    int x;
    char array [9];
};
int main(){
    Sample_union sample;
    cout<<sizeof(sample)<<endl;
    char test [9];
    cout<<sizeof(test)<<endl;
}

I test following code in different compilers, as well. 我也在不同的编译器中测试以下代码。

This happens because of padding. 这是由于填充而发生的。

If the union contains an int the compiler in this case wants to be sure that in an array of unions all the int s will be aligned to a 4-byte boundary. 如果联合包含int则在这种情况下,编译器要确保在联合数组中,所有int都将与4字节边界对齐。

char s on the other hand don't have alignment requirements, so there's no point in padding an array of 9 chars. 另一方面, char没有对齐要求,因此填充9个char数组毫无意义。

For example with g++ if you add a double member the size of the union becomes 16 (because double alignment is 8 bytes). 例如,对于g ++,如果添加一个double成员,则并集的大小将变为16(因为double对齐为8个字节)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM