实例讲解c语言结构体大小 sizeof(struct A)

约定为32位系统,即char 1字节、short 2字节、int 4字节

该问题总结为两条规律:
1,每个结构体成员的起始地址为该成员大小的整数倍,即int型成员的其实地址只能为0、4、8等

2,结构体的大小为其中最大成员大小的整数倍

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>

struct A{
	char a;
	int b;
	short c;
};
struct B{
	char a;
	short b;
	int c;
};
int main(int argc, char *argv[])
{
	printf("sizeof(struct A)=%d, sizeof(struct B)=%d\n", sizeof(struct A), sizeof(struct B));
	return 1;
}


结果:

分析:

struct A{
	char a;		//1
	int b;		//空3 + 4 = 7 (规则1)
	short c;	//2+空2=4 (规则2)
};
struct B{
	char a;		//1
	short b;	//空1 + 2 = 3 (规则1)
	int c;		//4
};

上面是问题的简化版,其实还有另外两条规则,下面严格按照定义补充完整:

1,数据类型自身对齐

数据类型的起始地址为其大小的整数倍

2,结构体的自身对齐

结构体的自身对齐值为其中最大的成员大小

3,指定对齐

可以使用关键词#pragma pack(1) 来指定结构体的对齐值

4,有效对齐值

有效对齐值为自身对齐值与指定对齐值中较小的一个。(即指定对齐值超过自身对齐值无意义)


依然使用上面的程序验证一下规则3:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>

#pragma pack(1)
struct A{
	char a;
	int b;
	short c;
};
#pragma pack(1)
struct B{
	char a;
	short b;
	int c;
};
int main(int argc, char *argv[])
{
	printf("sizeof(struct A)=%d, sizeof(struct B)=%d\n", sizeof(struct A), sizeof(struct B));
	return 1;
}
结果:

这个结果比较容易理解,struct成为了紧密型排列,之间没有空隙了。


验证规则4:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>

#pragma pack(8)
struct A{
	char a;
	int b;
	short c;
};
#pragma pack(8)
struct B{
	char a;
	short b;
	int c;
};
int main(int argc, char *argv[])
{
	printf("sizeof(struct A)=%d, sizeof(struct B)=%d\n", sizeof(struct A), sizeof(struct B));
	return 1;
}
结果:

与第一次结果相同,说明#pragma pack(8) 没有起到任何作用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

良非凉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值