代码:
#include "stdio.h"
int main()
{
char ch;
printf("sizeof(ch) = %d\n", sizeof(ch));
int a;
printf("sizeof(a) = %d\n", sizeof(a));
short b;
printf("sizeof(b) = %d\n", sizeof(b));
struct name1
{
char ch;
int num;
short x;
};
struct name1 n1;
printf("sizeof(n1) = %d\n", sizeof(n1));
struct name2
{
char ch;
short x;
int num;
};
struct name1 n2;
printf("sizeof(n2) = %d\n", sizeof(n2));
}
运行结果:
sizeof(ch) = 1
sizeof(a) = 4
sizeof(b) = 2
sizeof(n1) = 12
sizeof(n2) = 8
分析:
struct name1 n1:
假设 n1.ch 的起始地址是 0,那么 n1.num 的起始地址就是 4(结构体的每一个成员起始地址必须是自身类型大小的整数倍),n1.x 的起始地址就是 8,加起来就是 10 个字节,但是这不满足结构体大小必须是结构体占用最大字节数成员的整数倍(即 sizeof(int) 的整数倍),所以需要补充两个字节,总共 12 个字节。
struct name2 n2:
假设 n2.ch 的起始地址是 0,那么 n1.x 的起始地址就是 2(结构体的每一个成员起始地址必须是自身类型大小的整数倍),n1.x 的起始地址就是 4,加起来就是 8 个字节。