对于结构体,设置字节对齐,会改变成员布局和结构体大小
结构体大小分析:
1、默认情况下,结构体大小是最宽成员的整倍数,结构体的起始地址是最宽成员的整倍数,结构体的每个成员的起始地址是该成员宽度的整倍数
struct AA {
char a;
int b;
};
sizeof(struct AA); // = 8
struct AA {
char a;
short b
int c;
};
sizeof(struct AA); // = 8
字节对齐设置:
1、windows
#pragma pack(push, n) // 涉及当前对齐值压栈操作, 并把字节对齐值设为n
...
#pragma pack(pop) // 前面压栈的对齐值弹出
or
简单且通常用
#pragma pack(n) // 字节对齐值设置为n
...
#pragma pack() // 字节对齐值恢复默认
2、linux
packed 紧凑型:结构体的每个成员的起始地址是连续的
struct AA {
...
} __attribute__((packed, aligned(n)));
__attribute__((packed)); 相当于 __attribute__((packed, aligned(1)));
如 :
struct AA {
char a;
short b;
char c;
} __attribute__((packed, aligned(4)));
sizeof(struct AA); // = 4
struct AA {
char a;
short b;
short c;
} __attribute__((packed, aligned(4)));
sizeof(struct AA); // = 8
struct AA c1;
&c1.b; // maybe = 3215780217
&c1.c; // maybe = 3215780219, 内存布局完全是连续的成员之间无空隙的
非紧凑:
struct AA {
...
} __attribute__((aligned(n)));
如:
struct AA {
char a;
short b;
char c;
} __attribute__((aligned(4)));
sizeof(struct AA); // = 8;对比紧凑型