代码
#include <stdio.h>
struct test{
int i;
short c;
char *p;
};
int main(void)
{
struct test *pt = NULL;
printf("%p\n", &(pt->i));
printf("%p\n", &(pt->c));
printf("%p\n", &(pt->p));
printf("%lu\n", sizeof(struct test));
return 0;
}
Windows 10 x64上
编译输出了一下,发现size是16个字节
PS C:\Users\salamander\Desktop> ./test
0000000000000000
0000000000000004
0000000000000008
16
p的起始位置为什么变成了0000000000000008呢?
猜测是short后面补了2个字节,就是4+4了,指针本身应该是8个字节
的确是这样的.
n 字节的数据, 其地址要按照 n 字节来对齐.
int i
4字节, 默认处于处于 0, 对齐的.short c
2字节, 默认处于 4, 对齐的.指针
p
8字节, 默认处于 6, 没有按照8字节对齐, 所以在需要在其前面补两个字节.