【发布时间】:2016-09-18 12:58:49
【问题描述】:
自从我发现我的 sizeof() 运算符没有返回我预期的结果以来,我一直在学习结构数据填充。根据我观察到的模式,它将结构成员与最大的数据类型对齐。比如……
struct MyStruct1
{
char a; // 1 byte
char b; // 1 byte
char c; // 1 byte
char d; // 1 byte
char e; // 1 byte
// Total 5 Bytes
//Total size of struct = 5 (no padding)
};
struct MyStruct2
{
char a; // 1 byte
char b; // 1 byte
char c; // 1 byte
char d; // 1 byte
char e; // 1 byte
short f; // 2 bytes
// Total 7 Bytes
//Total size of struct = 8 (1 byte of padding between char e and short f
};
struct MyStruct3
{
char a; // 1 byte
char b; // 1 byte
char c; // 1 byte
char d; // 1 byte
char e; // 1 byte
int f; // 4 bytes
// Total 9 bytes
//Total size of struct = 12 (3 bytes of padding between char e and int f
};
但是如果让最后一个成员为 8 字节数据类型,例如 long long,它仍然只添加 3 个字节的填充,形成一个 4 字节对齐的结构。但是,如果我在 64 位模式下构建,它实际上会对齐 8 个字节(最大的数据类型)。我的第一个问题是,我说它使成员与最大的数据类型对齐是错误的吗?此语句对于 64 位构建似乎是正确的,但在 32 位构建中仅适用于最多 4 字节的数据类型。这与 CPU 的本机“字”大小有关吗?还是程序本身?
我的第二个问题是,以下是否会完全浪费空间和糟糕的编程?
struct MyBadStruct
{
char a; // 1 byte
unsigned int b; // 4 bytes
UINT8 c; // 1 byte
long d; // 4 bytes
UCHAR e; // 1 byte
char* f; // 4 bytes
char g; // 1 byte
// Total of 16 bytes
//Total size of struct = 28 bytes (12 bytes of padding, wasted)
};
谢谢。
【问题讨论】:
-
它根据可能与大小不同的对齐方式对齐。
char[42]的对齐方式为 1,即使它的大小为 42。您可以直接询问编译器数据类型与 alignof 的对齐方式是什么。doubles 发生了一件有趣的事情,否则它很简单。 -
有关发生的详细信息,请记住这取决于编译器和平台。发生这种情况的原因,请参阅stackoverflow.com/questions/381244/purpose-of-memory-alignment。
标签: c++ c struct padding memory-alignment