实例讲解c语言结构体大小 sizeof(struct A)
约定为32位系统,即char 1字节、short 2字节、int 4字节
该问题总结为两条规律:
1,每个结构体成员的起始地址为该成员大小的整数倍,即int型成员的其实地址只能为0、4、8等
该问题总结为两条规律:
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) 没有起到任何作用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?