结构体对齐(The alignment of structure)
来源:互联网 发布:c语言中mod是什么意思 编辑:程序博客网 时间:2024/06/04 08:04
THE ALIGMENT OF STRUCTURE
结构体的对齐
也许很少有人会关心结构体的对齐问题,毕竟这牵涉到硬件。以下是对结构体对齐的总结。
首先,先说对齐模数。这里不具体定义它了,用的时候知道它是什么以及怎么用的就可以了。以下是windows和Linux中的对齐模数。
windows中
char short int long double long double
长度 1 2 4 4 8 8
模数 1 2 4 4 8 8
linux中
char short int long double long double 长度 1 2 4 4 8 12 模数 1 2 4 4 4 4
计算时大概分两个步骤:
1. 先计算变量。根据对齐模数计算结构体变量中的起始地址,必须是对齐模数的整数倍,不是整数倍会自动补齐。
2. 在计算结构体。根据结构体的对齐模数计算结构体的大小。结构体的对齐模数是#pragma pack定义的模数与结构体内部最大的基本数据类型成员长度中数值较小者。结构体的长度应该是该模数的整数倍。
#pragma pack(2)//#pragma为编译指示
struct mystruct{
char a;
long double b;
};
#pragma pack()
根据步骤1,先计算变量。对char,对齐模数为1,从0(0是1的整数倍)开始,接着对long double,对齐模数为8,而1不是8的整数倍,故补齐7个字节,起始地址从8开始,现在总大小为16。
根据步骤2,计算结构体。结构体对齐模数是结构体内部最大数据成员长度和pragma pack中较小者,前者为8后者为2,所以结构体对齐模数是2。而此时,大小为16,是2的整数倍,不再对齐。故最终,大小为16。
记住,对齐模数很重要。Win32中,int为4个字节,只有短(short)int时才是2个字节,而double不论何种double都是8。而Linux模数只有三个数1,2,4。记住不难。
- 结构体对齐(The alignment of structure)
- Alignment of structure
- 数据的字节对齐(data structure alignment)
- 内存对齐(Data Structure Alignment)
- 代码对齐(Alignment of Code)
- Alignment of the Planets
- Alignment of the Planets
- Alignment of a structure, a tricky issue
- 关于结构体数据对齐(About data alignment)
- Android的工程结构(The structure of Android Project)
- The Structure of CICS
- The structure of GetMessage()
- Structure of the flower
- The Structure of jQuery
- Alignment of Code (代码对齐)UVA1593
- 1224 Structure of the Protocol
- the writting structure of ielts
- Data structure alignmentData structure alignment
- struts 2.0的Action讲解
- USACO算法系列八——fact4
- 网游开发中选择线程模型的思考
- 游戏服务器中的数据库异步操作技术和游戏数据的保存机制
- SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTIT区别
- 结构体对齐(The alignment of structure)
- junit jumpstart
- 关于xsniff
- cannot instantiate the type
- 关于数据库内连接外连接左连接右连接
- 深入理解Android消息处理系统——Looper、Handler、Thread
- 10年10月10日
- 使用Chromium尝试WebGL
- 我要积分 我要积分