The problem of byte alignment?

< H1 > Code < / H1 >
-sharpinclude <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;
}

is compiled and output on

Windows 10x64, and it is found that size is 16 bytes

.
PS C:\Users\salamander\Desktop> ./test
0000000000000000
0000000000000004
0000000000000008
16
Why did the starting position of

p become 00000000000008?
guess that 2 bytes are added after short, which is 4 bytes, and the pointer itself should be 8 bytes

Mar.23,2021

that's true.

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 bytes of data whose address should be aligned according to n bytes.

int I 4 bytes, default at 0, aligned.
short c 2 bytes, default at 4, aligned.
pointer p 8 bytes, default is 6, not aligned according to 8 bytes, so two bytes need to be added before it.

Menu