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? 我該如何解決它?
哪個編譯器? – Macmade
我想你可能需要添加一個名爲** packed **的屬性到結構中來刪除額外的填充。 – Vikyboss
填充。請參閱http://stackoverflow.com/a/18654110/12711 –