23、字节对齐
struct AlignedStruct {char a; // 本来1字节,padding 3 字节int b; // 4 字节short c; // 本来 short 2字节,但是整体需要按照 4 字节对齐(成员对齐边界最大的是int 4) // 所以需要padding 2// 总共: 4 + 4 + 4
};struct MyStruct {double a; // 8 个字节char b; // 本来占一个字节,但是接下来的 int 需要起始地址为4的倍数//所以这里也会加3字节的paddingint c; // 4 个字节// 总共: 8 + 4 + 4 = 16
};
分析 struct MyStruct
的对齐情况。
double a
占用 8 个字节,起始地址为 0。char b
占用 1 个字节,起始地址为 8。- 为了使
int c
对齐到 4 字节边界,需要在char b
后面填充 3 个字节的 padding,因此int c
的起始地址为 12。 int c
占用 4 个字节,起始地址为 12。
因此,struct MyStruct
的总大小为 16 个字节。
为了进一步验证,我们可以编写一个简单的 C++ 程序来检查结构体的大小:
#include <iostream>struct MyStruct {double a;char b;int c;
};int main() {std::cout << "Size of MyStruct: " << sizeof(MyStruct) << " bytes" << std::endl;return 0;
}
运行这个程序,会发现 MyStruct
的大小确实是 16 个字节。
总结:struct MyStruct
的对齐之后的大小是 16 个字节,而不是 24 个字节。
AlignedStruct 为什么是 12 呢 ?
详细分析 struct AlignedStruct
的对齐情况:
char a
占用 1 个字节,起始地址为 0。- 为了使
int b
对齐到 4 字节边界,需要在char a
后面填充 3 个字节的 padding,因此int b
的起始地址为 4。 int b
占用 4 个字节,起始地址为 4。short c
占用 2 个字节,起始地址为 8。- 为了使整个结构体的大小是
int
的倍数(最大对齐边界),需要在short c
后面填充 2 个字节的 padding。
因此,struct AlignedStruct
的总大小为 12 个字节。
为了进一步验证,我们可以编写一个简单的 C++ 程序来检查结构体的大小:
#include <iostream>struct AlignedStruct {char a;int b;short c;
};int main() {std::cout << "Size of AlignedStruct: " << sizeof(AlignedStruct) << " bytes" << std::endl;return 0;
}
运行这个程序,会发现 AlignedStruct
的大小确实是 12 个字节。
总结:struct AlignedStruct
的对齐之后的大小是 12 个字节。