当前位置:网站首页>结构体大小计算--结构体内存对齐
结构体大小计算--结构体内存对齐
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为例,优秀的结构体设计可以节省不少内存。
注:修改完默认对齐数后别忘了改回去!
边栏推荐
- .NET静态代码织入——肉夹馍(Rougamo) 发布1.1.0
- ue先视频教程后深入
- MySQL Advanced - MVCC (ultra-detailed finishing)
- Go inside the basic knowledge
- 实例027:递归输出
- pointer arithmetic in c language
- MySQL 23 classic interviews hang the interviewer
- 【暑期每日一题】洛谷 P1255 数楼梯
- 速看!PMP新考纲、PMBOK第七版解读
- System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security
猜你喜欢

The second day HCIP

速看!PMP新考纲、PMBOK第七版解读

第06章 索引的数据结构【2.索引及调优篇】【MySQL高级】

Go inside the basic knowledge

解决:- SPY: No data found for this date range, symbol may be delisted报错

实例027:递归输出

MySql 5.7.38 download and installation tutorial, and realize the operation of MySql in Navicat

MPLS的相关技术
![[数据集][VOC]男女数据集voc格式6188张](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[数据集][VOC]男女数据集voc格式6188张

MySQL - Multi-table query and case detailed explanation
随机推荐
yml字符串读取时转成数字了怎么解决
MySQL high-level --- storage engine, index, lock
Kind of weird!Access the destination URL, the host can container but not
2022年7月18日-7月31日(Ue4视频教程和文档,20小时。合计1412小时,剩8588小时)
ue先视频教程后深入
Two good php debug tutorials
Servlet
Node installation and environment configuration
Launch Space on-premises deployment (local) Beta!
张驰课堂:六西格玛测量系统的误差分析与判定
技术管理三级跳
(部分不懂,笔记整理未完成)【图论】差分约束
Understand C operators in one article
享年94岁,图灵奖得主、计算复杂性理论先驱Juris Hartmanis逝世
The nacos source code can not find the istio package
.NET静态代码织入——肉夹馍(Rougamo) 发布1.1.0
Nodejs installation and global configuration (super detailed)
PHP Warning: putenv() has been disabled for security reasons in phar
Dataset:机器学习中常用数据集下载链接集合之详细攻略
MySQL driver jar package download -- nanny tutorial