0

代码

#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个字节

Salamander 6.4k
2018-07-03 提问
1 个回答
1

已采纳

的确是这样的.

A memory access is said to be aligned when the datum being accessed is n bytes long and the datum address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned.

n 字节的数据, 其地址要按照 n 字节来对齐.

int i 4字节, 默认处于处于 0, 对齐的.
short c 2字节, 默认处于 4, 对齐的.
指针 p 8字节, 默认处于 6, 没有按照8字节对齐, 所以在需要在其前面补两个字节.

撰写答案

推广链接