typedef struct {
unsigned char a, b;
unsigned int c;
unsigned short d;
unsigned int e;
} ABC;
unsigned short code1[6] = {0x1607,0x1003,0x1008,0x2001,0x3002,0x4003};
ABC *p = (ABC*)&code1[0];
printf("%X", p->c); // 輸出 0x20011008 而非預期 0x1008100332 位編譯器對 unsigned int 要求 4 字節對齊。結構體內存佈局:
offset 0: a (1B)
offset 1: b (1B)
offset 2-3: padding (2B) // 對齊 c
offset 4-7: c (4B) // 取自 code1[2]、code1[3] 即 0x1008, 0x2001 → 0x20011008 (小端)
offset 8-9: d (2B)
offset 10-11: padding (2B) // 對齊 e
offset 12-15: e (4B)d (short) 移到 c 前,消除 padding。typedef struct { unsigned char a,b; unsigned short d; unsigned int c,e; } ABC;typedef struct { unsigned char a,b; unsigned char c[4]; unsigned char d[2]; unsigned char e[4]; } ABC;讀取時手動組裝(考慮大小端)。#pragma pack(1) 或 __attribute__((packed)) 取消對齊(可能降低訪問性能)。