当前位置:网站首页>结构体大小计算--结构体内存对齐
结构体大小计算--结构体内存对齐
2022-08-02 06:20:00 【风吹电风扇】
1.对齐规则
结构体的内存大小是根据其内存对齐的结果计算得来的,对齐遵循以下规则:
1. 第一个成员在与结构体变量偏移量为0的地址处。
2. 其他成员变量要对齐到对齐数的整数倍的地址处。
(对齐数 = 编译器默认的一个对齐数 与 该成员大小的较小值。)
3 .结构体的总大小位最大对齐数的整数倍。
2.计算演示
代码
struct A
{
char ch;
short num1;
int num2;
};
struct B
{
char ch;
int num2;
short num1;
};
int main()
{
printf("%u %u", sizeof(struct A), sizeof(struct B));
}
结果
可是结构体A和结构体B的内容是完全一样的,为什么计算出的大小不同?
过程分析
注:VS中的默认对齐数为8
结构体A
1. 将char类型数据排在偏移量为0的位置,char的大小为1,对齐数取8(VS中的默认对齐数)和1的较小值为12.将short类型放到2的整数倍位置(2和8的较小值)
3.再将int类型放到4(4和 8的最小值)的整数倍位置。
同理结构体B占12字节,如下图所示:
3.修改默认对齐数
#pragma pack()
例子
#pragma pack(8)//设置默认对齐数为8
#pragma pack(1)//设置默认对齐数为1
#pragma pack()取消设置的默认对齐数,还原为默认
用处:让程序员能够更好的设计结构体就以上面同样内容的结构体A和B为例,优秀的结构体设计可以节省不少内存。
注:修改完默认对齐数后别忘了改回去!
边栏推荐
猜你喜欢
Leading the demand and justifying the HR value - the successful launch of the "Human Resource Leading Model HRLM"
MPLS的相关技术
实例026:递归求阶乘
张驰课堂:六西格玛培训工具——箱线图
实例027:递归输出
MySQL Advanced - MVCC (ultra-detailed finishing)
Go inside the basic knowledge
SphereEx苗立尧:云原生架构下的Database Mesh研发实践
APP special test: traffic test
张驰课堂:六西格玛测量系统的误差分析与判定
随机推荐
Servlet
数据库概论之MySQL表的增删改查1
MySQL 5.7 installation tutorial (full-step, nanny-level tutorial)
有点奇怪!访问目的网址,主机能容器却不行
Dataset:机器学习中常用数据集下载链接集合之详细攻略
APP专项测试:流量测试
PHP Warning: putenv() has been disabled for security reasons in phar
Connection reset by peer problem analysis
Revitalize rural circular economy and digital chain to link agricultural "ecological chain"
【21天学习挑战赛】顺序查找
SphereEx苗立尧:云原生架构下的Database Mesh研发实践
Launch Space on-premises deployment (local) Beta!
System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security
The nacos source code can not find the istio package
实例030:回文数
FaceBook社媒营销高效转化技巧分享
能与观众实时互动的Claper
(Notes are not completed) [Graph Theory] Traversal of graphs
Go inside the basic knowledge
In-depth analysis of the initialization of member variables and local variables