結構體成員在記憶體中並非緊密排列,編譯器依自然對齊規則插入填充位元組。#pragma pack(n) 允許開發者指定最大對齊邊界,影響結構體大小與成員偏移。
#pragma pack(8) /* 設定 8 位元組對齊 */
struct MyStruct { ... };
#pragma pack() /* 恢復預設對齊 */
n 通常為 1, 2, 4, 8, 16。GCC/Clang 亦支援 __attribute__((packed))、__attribute__((aligned(n)))。
#pragma pack(8)
struct S1 { short a; long b; }; // short=2, long=4
struct S2 { char c; S1 d; long long e; }; // long long=8
#pragma pack()
a (short, 2 bytes):有效對齊 = min(2,8)=2 → 偏移 0,佔 0-1b (long, 4 bytes):有效對齊 = min(4,8)=4 → 偏移 4 (0-1 後補 2 bytes 填充),佔 4-7c (char, 1 byte):有效對齊 = min(1,8)=1 → 偏移 0d (S1, 8 bytes):S1 最大有效對齊為 4 → 有效對齊 = min(4,8)=4 → 偏移 4 (補 3 bytes),佔 4-11e (long long, 8 bytes):有效對齊 = min(8,8)=8 → 偏移 16 (12-15 補 4 bytes),佔 16-23
S1: [a:2][pad:2][b:4] = 8 bytes
S2: [c:1][pad:3][d:8][pad:4][e:8] = 24 bytes
0 4 12 16 24
min(自身大小, pack值) 對齊typedef char A[3]; 對齊仍為 1,非 3#pragma pack(1)