我是结构对齐和打包的新手。我以为我明白了,但我发现了一些我没想到的结果(见下文)。
我对结构对齐的理解是:
类型通常在其大小的倍数的内存地址上对齐。
根据需要添加填充以促进正确对齐
结构的末尾必须填充到最大元素的倍数(以方便数组访问)
该#pragma pack
指令基本上允许覆盖基于类型大小对齐的一般约定:
#pragma pack(push, 8)
struct SPack8
{
// Assume short int is 2 bytes, double is 8 bytes, and int is 4 bytes
short int a;
double b;
short int c;
int d;
};
#pragma pack(pop)
Pseudo struct layout: What I expected:
// note: PADDING IS BRACKETED
0, 1, [2, 3, 4, 5, 6, 7] // a occupies address 0, 1
8, 9, 10, 11, 12, 13, 14, 15, // b occupies 8-15 inclusive
16, 17, [18, 19, 20, 21, 22, 23] // c occupies 16-17 inclusive
24, 25, 26, 27 // d occupies 24-27 inclusive
// Thus far, SPack8 is 28 bytes, but the structure must be a multiple of
// sizeof(double) so we need to add padding to make it 32 bytes
[28, 29, 30, 31]
令我惊讶的是,在 VS 2015 x86 上 sizeof(SPack8) == 24。似乎 d 没有在 8 字节地址上对齐:
offsetof(SPack, a) // 0, as expected
offsetof(SPack, b) // 8, as expected
offsetof(Spack, c) // 16, as expected
offsetof(SPack, d) // 20..what??
有人可以解释发生了什么/我误解了什么吗?
谢谢!