每個成員依其自然對齊需求放置:
char:1 位元組對齊short:2 位元組對齊int, long, float:4 位元組對齊double:8 位元組對齊編譯器會在成員間插入填充位元組,並在結構體尾端補齊使總大小為對齊單位的整數倍。
struct test {
char x1; // offset 0
short x2; // offset 2 (填充 1 byte)
float x3; // offset 4
char x4; // offset 8
}; // 尾端填充 3 bytes,總大小 12
#pragma pack(n):指定 n 位元組對齊(n = 1,2,4,8,16...)。#pragma pack():恢復預設對齊。__attribute__((aligned(n)))、__attribute__((packed))。#pragma pack(8)
struct s1 { short a; long b; }; // 大小 8,b 4-byte 對齊
struct s2 { char c; s1 d; long long e; }; // 大小 24
#pragma pack()
關鍵規則:
min(成員大小, pack值)。記憶體佈局:
s1: aa.. bbbb (.. 表填充)
s2: c... aa.. bbbb .... eeeeeeee (共 24 bytes)
陣列對齊等同其元素類型(char[3] 仍為 1-byte 對齊),typedef 不改變對齊特性。
sizeof == 1,確保實例位址唯一。