2012-03-04 19 views
0

可能重複:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?爲什麼char變量的大小在結構體內部和外部從4變爲1?

下面是代碼:

#include <stdio.h> 

struct small{ 
    int a; 
    int b; 
    char c; 
}; 

void main(){ 
    printf("The size of int is: %d\n",(int)sizeof(int)); 
    printf("The size of char is: %d\n",(int)sizeof(char)); 
    printf("The size of small is: %d\n",(int)sizeof(struct small)); 
} 

這裏是輸出:

The size of int is: 4 
The size of char is: 1 
The size of small is: 12 

我預計小尺寸爲9,但它原來是12

+5

您的期望完全錯誤。沒有人說結構的大小是其成員大小的總和。 – 2012-03-04 22:25:16

+5

這是因爲對齊限制。在這裏已經有數百次的問題了。 – Coren 2012-03-04 22:25:37

+0

要添加上面的註釋,請查看stddef.h中的'offsetof'宏。它評估結構中給定成員的偏移量(以字節爲單位) – pmohandas 2012-03-04 22:31:53

回答

1

這是因爲對齊的要求。如果你申報的struct small秒的數組:

struct small arr[10]; 

然後每個元素的a會立即前面的元素之後。在你的系統上,顯然,int需要按照絕對要求對齊到四字節邊界—,或者僅僅爲了最優性能—因此struct small包括三個字節的填充以確保後續的struct small的正確對齊。

相關問題