实例讲解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) 没有起到任何作用。

posted @   SymPny  阅读(279)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示