#include <stdio.h>
struct foo1
{
char *p;
char c;
long x;
};
int main(void)
{
printf("char * size: %d\n", sizeof(char *));
printf("char size: %d\n", sizeof(char));
printf("long size: %d\n", sizeof(long));
putchar('\n');
printf("foo1 size: %d\n", sizeof(struct foo1));
putchar('\n');
struct foo1 tmp;
printf("&tmp = 0x%X\n", &tmp);
printf("&tmp.p = 0x%X\n", &tmp.p);
printf("&tmp.c = 0x%X\n", &tmp.c);
printf("&tmp.x = 0x%X\n", &tmp.x);
return 0;
}
char * size: 4
char size: 1
long size: 4
foo1 size: 12
&tmp = 0x1DFE4C
&tmp.p = 0x1DFE4C
&tmp.c = 0x1DFE50
&tmp.x = 0x1DFE54
请按任意键继续. . .
tmp的地址是 0x1DFE4C
因为p是tmp的第一个元素,所以tmp.p的地址也是 0x1DFE4C
因为p是char *类型 , 大小是4个字节,所以tmp.c的地址从 0x1DFE50 开始(0x1DFE4C + 4 = 0x1DFE50)
因为c是char 类型 ,大小是1个字节,所以tmp.x从0x1DFE51开始?
不,因为要对齐,所以tmp.x从 0x1DFE54开始(4字节对齐)
0x1DFE51 0x1DFE52 0x1DFE53 这3个内存空间就浪费了
你现在能明白为什么 foo1 size: 12 了吗? |