结构体中的字节对齐 |
您所在的位置:网站首页 › 字节对齐方式 › 结构体中的字节对齐 |
GCC 特有写法
__attribute__ 可以让结构体成员对齐在n字节的边界上. __attribute__((pack)) //取消优化对齐,按照实际用的字节数对齐 __attribute__((aligned(4))) //按照4字节对齐,其中参数必须是2的幂 ("positive power of 2") 举个栗子: struct struct1 { char str1[2]; char str2[3]; }; struct struct2 { char str1[2]; char str2[3]; }__attribute__((pack)); struct struct3 { char str1[2]; char str2[3]; }__attribute__((aligned(4))); struct struct4 { char str1[2]; char str2[3]; char str1[2]; }__attribute__((aligned(2))); typedef struct { char str1[2]; char str2[3]; } __attribute__((packed)) struct5;sizeof()出来的结果为 struct1 -> 一般会是5 struct2 -> 5 struct3 -> 8 struct4 -> 8 struct5 -> 5 在一连串的通信协议中,把一条命令分隔成了结构体管理的时候,需要加上 __attribute__((packed)) 来确保长度的正确。
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |