我对“数据对齐”这件事非常困惑:
#include <stdio.h>
int main(){
    struct st{
        int i,*p;
        char c;
        union { char type[4]; unsigned char d;} un; 
    };
    struct st s1={25,&a,'X',"asdf"};
    printf("sizeof s1 is %d",sizeof(s1));
    return 0;
}由于数据对齐,我认为由于
int i : 4 bytes
int *p : 8 bytes
char c : 1 byte(+3)
union : 4 bytes输出为20,但这将输出sizeof s1 is 24!为什么它输出24?这是否考虑到int *p,即8字节?
发布于 2013-12-12 03:18:38
在您使用的体系结构中,int *p是8字节,但也需要在8字节的边界上。这在i和p之间提供了4个字节的衬垫。此外,由于int *p需要位于8字节的边界上,所以总体结构需要是8字节的倍数,这样它们的数组总是对p有正确的对齐。
所以,你最终得到了这样的布局:
i:4字节,对齐4p:8字节,对齐8字节c:1字节un:4个字节(因为它可以保持字节对齐)https://stackoverflow.com/questions/20534343
复制相似问题