)
1.铺垫请问这2个结构体的所占内存空间是多少struct S1 { char ch1; int i; char ch2; }; struct S2 { char ch1; char ch2; int i; };是不是都是6呢答案是错误的。用 sizeof 来计算这2个结构体的大小。printf(%d\n, sizeof(struct S1)); printf(%d\n, sizeof(struct S2));可以发现只是这2个结构体的成员变量的顺序不同大小就会差4个字节。那么这就涉及到结构体在内存中的对齐方式有关。2.结构体的对齐规则结构体是如何对齐的呢结构体对齐的规则1第一个变量在结构体变量偏移量为0的地址处。什么是偏移量 : 变量距离结构体的起始地址的有几个字节距离就是多少偏移量。2其他成员变量要对齐到对齐数的整数倍的地址处。对齐数编译器默认的一个对齐数与该成员的较小值。3结构体的总大小为所有结构体成员中最大对齐数的整数倍。4如果嵌套了结构体的情况嵌套的结构体对齐到自己的最大对齐数的整数倍结构体的整体大小就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍。3.画图说明结构体的对齐方式我的编译器的对齐数是8编译器不同可能默认对齐数不同也可能对齐数是变量自身字节大小。Struct S1:是不是真的向上面的画图一样呢用offsetof验证S1画图offsetof是用来计算偏移量的宏。#includestddef.h #includestdio.h struct S1 { char ch1; int i; char ch2; }; struct S2 { char ch1; char ch2; int i; }; int main() { printf(%d\n, offsetof(struct S1, ch1)); printf(%d\n, offsetof(struct S1, i)); printf(%d\n, offsetof(struct S1, ch2)); return 0; }这个函数证明以上画图是正确的。所以struct S1 类型结构体的总大小是12个字节。结构体在内存中有一定的内存浪费。struct S2:用offsetof验证S2画图int main() { printf(%d\n, offsetof(struct S2, ch1)); printf(%d\n, offsetof(struct S2, ch2)); printf(%d\n, offsetof(struct S2, i)); return 0; }S2的画图也是没问题的。strust S4(嵌套结构体)struct S3 { double d; char ch; int i; }; struct S4 { char ch; struct S3 s; double d; }; int main() { printf(%d\n, sizeof(struct S4)); return 0; }用offsetof验证S4画图int main() { printf(%d\n, offsetof(struct S4, ch)); printf(%d\n, offsetof(struct S4, s)); printf(%d\n, offsetof(struct S4, d)); return 0; }以上就是结构体内存对齐的所有内容了。