规则
1. 结构体中元素按照定义顺序一个一个放到内存中,
每个元素放置到内存中时,它都会认为是以它自己的大小划分,
因此放置位置一定会在自己宽度的整数倍
2. 结构体对齐到最大元素的整数倍
3. 基本数据类型的对齐大小为自身大小,
但结构体数据类型的对齐大小为其元素中最大对齐大小元素的大小
4. 数组看作连续数个相同类型元素
举例
struct st {
char c;//1
int i;//4
double d;//8
};
sizeof(st) = 16 (4+4+8)
struct st {
char c;//1
double d;//8
int i;//4
};
sizeof(st) = 24 (8+8+8) 应用规则2
使用有效对齐值
#pragma pack(4) 可以指定有效对齐值,1,2,4,8,16
那么规则简化为
1. 每个成员的偏移都是 该成员大小与有效对齐值中较小那个 的整数倍
2. 结构体总大小为有效对齐值的整数倍