结构填充的规则是什么

时间:2019-04-23 04:54:59

标签: c structure padding

我在geeksforgeeks中浏览了一篇有关结构填充的文章,https://www.geeksforgeeks.org/is-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/ 但是我不知道为什么会这样:

int main() 
{ 

    struct C { 
        // sizeof(double) = 8 
        double z; 

        // sizeof(short int) = 2 
        short int y; 
        // Padding of 2 bytes 

        // sizeof(int) = 4 
        int x; 
    }; 

    printf("Size of struct: %d", sizeof(struct C)); 

    return 0; 
} 

我知道y(短整数)后跟x(整数),因此在y之后需要填充。但是为什么这里的填充是2?

1 个答案:

答案 0 :(得分:1)

编译器希望将int对齐到四个字节的边界上,并且该边界短了两个字节,因此填充被计算为两个字节:

struct C { 
    // offset = 0
    double z; 
    // offset = 8
    short int y; 
    // offset = 10
    // ... padding ...
    // offset = 12
    int x; 
    // offset = 16
}; 

大于10的4的下一个倍数是12。

编辑:实际上,结构是按照此算法(伪代码)对齐的:

offset = 0;
alignment = 1;
for each field in structure {
    offset = (offset + field.alignment - 1) / field.alignment * field.alignment;
    field.offset = offset;
    alignment = lcm(alignment, field.alignment);
}
structure.alignment = alignment;
structure.size = (offset + alignment - 1) / alignment * alignment;