问题描述
我已经阅读到sizeof联合会在联合会中提供最大的成员人数。但是当我这样做时:我得到了意外的结果:
#include <iostream>
using namespace std;
union recordtype
{
int arr[9];
double x;
};
int main()
{
recordtype t;
cout << sizeof(t); //output is 40,instead of 36 (9*4bytes each)
}
为什么大小为40而不是36,即使我将数组更改为“ int arr [10]”,那么sizeof的输出也为40(与“ int arr [9]”的情况相同)内部发生在这里?
解决方法
由于double
是后端的64位类型,因此编译器将使用额外的32位或4个字节填充union
的大小,以对齐int
和{ {1}}。这样,无论哪个成员处于活动状态,double
都将对齐为64位。
如果您改用union
创建联合,则它的大小很可能为float
,因为不需要这种对齐。
36
请注意,此行为是实现定义的,并且理论上union U
{
int arr[9];
float x;
};
也有32位大的可能。因此,您永远不要依赖它。