鍍金池/ 問答/Java  C  網(wǎng)絡安全/ 字節(jié)對齊的問題?

字節(jié)對齊的問題?

代碼

#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上
編譯輸出了一下,發(fā)現(xiàn)size是16個字節(jié)

PS C:\Users\salamander\Desktop> ./test
0000000000000000
0000000000000004
0000000000000008
16

p的起始位置為什么變成了0000000000000008呢?
猜測是short后面補了2個字節(jié),就是4+4了,指針本身應該是8個字節(jié)

回答
編輯回答
陪我終

的確是這樣的.

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 字節(jié)的數(shù)據(jù), 其地址要按照 n 字節(jié)來對齊.

int i 4字節(jié), 默認處于處于 0, 對齊的.
short c 2字節(jié), 默認處于 4, 對齊的.
指針 p 8字節(jié), 默認處于 6, 沒有按照8字節(jié)對齊, 所以在需要在其前面補兩個字節(jié).

2018年9月15日 14:23