首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C 語言結構體內存對齊陷阱:數組強制轉換導致字段錯位的根因與解決方案

     編輯:程式設計疑難解答

現象

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 而非預期 0x10081003

原因

32 位編譯器對 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)

解決方案

  1. 重排字段:將 d (short) 移到 c 前,消除 padding。
    typedef struct { unsigned char a,b; unsigned short d; unsigned int c,e; } ABC;
  2. 按字節定義:
    typedef struct { unsigned char a,b; unsigned char c[4]; unsigned char d[2]; unsigned char e[4]; } ABC;
    讀取時手動組裝(考慮大小端)。
  3. 打包屬性:#pragma pack(1) 或 __attribute__((packed)) 取消對齊(可能降低訪問性能)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved