struct S1 { char a; short b; char c; }; // sizeof=6 struct S2 { char a; char b; short c; }; // sizeof=4
offset 0: char a (size 1)
offset 1: padding 1 (對齊 short)
offset 2: short b (size 2, offset 2%2==0)
offset 4: char c (size 1)
offset 5: padding 1 (總大小對齊 2 的倍數 → 6)
Total: 6 bytes
offset 0: char a
offset 1: char b
offset 2: short c (offset 2%2==0, 無需填充)
offset 4: 結束
Total: 4 bytes
#pragma pack#pragma pack(push) // 保存當前對齊設置 #pragma pack(1) // 設置 1 字節對齊(無填充) struct Packed { char a; short b; char c; }; // sizeof = 4 #pragma pack(pop) // 恢復默認對齊
#pragma pack(n):指定最大對齊數,成員按 min(sizeof(類型), n) 對齊。push/pop 配對使用,避免全局污染。// 強制 n 字節對齊 struct __attribute__((aligned(8))) Aligned8 { char a; double d; }; // 取消優化對齊,按實際大小緊湊排列 struct __attribute__((packed)) PackedGCC { char a; short b; };
int arr[10] 視為 10 個獨立 int 依次排列,各自對齊,整體對齊按 int(4 字節)。
offsetof 看成員偏移。