可能重複:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
Extra bytes when declaring a member of a struct as uint32_tSizeof運算符返回不正確的大小?
出於某種原因,該sizeof
操作者返回一個假的尺寸爲這樣的結構(的48
代替40
):
typedef struct mbdb_file_info {
uint16_t mode;
uint32_t unk0;
uint32_t unk1;
uint32_t user_id;
uint32_t group_id;
uint32_t time0;
uint32_t time1;
uint32_t time2;
uint64_t length;
uint8_t flag;
uint8_t property_count;
} mbdb_file_info;
因此,這裏是一個簡單的測試:
printf("%ld %ld %ld %ld: %ld", sizeof(uint8_t),
sizeof(uint16_t),
sizeof(uint32_t),
sizeof(uint64_t),
sizeof(mbdb_file_info));
它打印:
1 2 4 8:48
這是如何發生的呢?如果您將所有尺寸一起添加,您可以獲得40
,而不是48
。 48
從哪裏來?
如果有些奇怪的x86-64
perk,我該如何確保結構的所有字段佔用我希望它們佔據的數量(我正在爲此結構投擲一堆字節)?
哦,所以我需要'volatile struct'? –
您需要添加'__attribute __((packed))'。 –
@Nick請注意,使用'packed' *可能會影響程序的性能。未對齊的內存訪問可能比對齊的訪問更昂貴,並且可能會在循環中產生可衡量的差異。 –