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
您的期望完全錯誤。沒有人說結構的大小是其成員大小的總和。 – 2012-03-04 22:25:16
這是因爲對齊限制。在這裏已經有數百次的問題了。 – Coren 2012-03-04 22:25:37
要添加上面的註釋,請查看stddef.h中的'offsetof'宏。它評估結構中給定成員的偏移量(以字節爲單位) – pmohandas 2012-03-04 22:31:53