2016-04-02 41 views
2

我有這樣的代碼:GCC生成錯誤的結構偏移爲什麼?

mbr.h:

struct mbr_partition { 
       char flags; 
       char start_head; 
       char start_sector; 
       char start_cyl; 
       char type; 
       char last_head; 
       char last_sector; 
       char last_cyl; 
       uint32_t start; 
       uint32_t size; 
     }; 

     struct mbr { 
       char bootloader[446]; 
       struct mbr_partition partition1; 
       struct mbr_partition partition2; 
       struct mbr_partition partition3; 
       struct mbr_partition partition4; 
       char magic[2]; 
     }; 

和:main.c中:

int main() 
{ 
     printf("%d\n", sizeof(struct mbr)); 
     printf("%d\n", sizeof(struct mbr_partition)); 
     printf("%d\n", sizeof(long)); 
     struct mbr mbr; 
     printf("%d, %d\n", ((char *) &mbr.magic) - ((char *) &mbr), sizeof(mbr)$ 
     printf("1: %d\n", ((char *) &mbr.partition1) - ((char *) &mbr)); 
     printf("2: %d\n", ((char *) &mbr.partition2) - ((char *) &mbr)); 
     printf("3: %d\n", ((char *) &mbr.partition3) - ((char *) &mbr)); 
     printf("4: %d\n", ((char *) &mbr.partition4) - ((char *) &mbr)); 
     return 0; 
} 

輸出:

516 
16 
8 
512, 516 
1: 448 
2: 464 
3: 480 
4: 496 

爲什麼大小是516個字節(它應該是512)? 爲什麼partition1的偏移量是448而不是446? 我該如何解決它?

+0

哪個編譯器? – Macmade

+2

我想你可能需要添加一個名爲** packed **的屬性到結構中來刪除額外的填充。 – Vikyboss

+1

填充。請參閱http://stackoverflow.com/a/18654110/12711 –

回答

7

因爲可能有一些填充字節或填充位。

從N1570 6.7.2.1 Structure and union specifiers引用:(重點煤礦)

15內的結構對象,非位字段構件和單元,其中 位字段駐留有,在順序 增加地址在那裏他們宣佈。指向結構對象的指針(適當地爲 轉換)指向其初始成員(或者如果該成員是位域,則返回其所在的單位),反之亦然。 在結構對象內可能存在未命名的填充,但不在其開頭。