#pragma pack(n) 強制指定#pragma pack(2)
struct C {
char b; // 偏移 0, 大小 1
int a; // 有效對齊 2, 偏移 2, 大小 4 (佔 2,3,4,5)
short c; // 有效對齊 2, 偏移 6, 大小 2 (佔 6,7)
}; // 總大小 8 (最大有效對齊 2 的倍數)
#pragma pack()
改為 pack(4) 時 a 偏移 4,總大小 12。
#pragma pack(8)
struct S1 { char a; long b; }; // 大小 8 (b 對齊 4, 尾部填充 3)
struct S2 {
char c; // 偏移 0
struct S1 d; // 對齊 4, 偏移 4, 大小 8
long long e; // 對齊 8, 偏移 16, 大小 8
}; // 總大小 24 (最大有效對齊 8 的倍數)
#pragma pack()
// 差:大小交替,產生大量填充
struct Bad { char a; int b; char c; short d; }; // 12-16 字節
// 優:小類型聚集
struct Good { char a; char c; short d; int b; }; // 8-12 字節
struct Aligned {
char a;
char reserved[3]; // 顯式填充,文檔化對齊意圖
int b;
};
(unsigned short*)(p+1) 從奇地址訪問 short,x86 降速,MIPS/Sparc 崩潰pack 設置__attribute__((packed)))offsetof 驗證成員偏移