简体   繁体   English

结构填充如何在下面的代码片段中发生

[英]How does structure padding take place in the below snippet of code

I am using a structure, but unable to understand how the padding occurs.我正在使用一个结构,但无法理解填充是如何发生的。 I am using a 64-bit system.我使用的是 64 位系统。 The size of char is 1 byte, float is 4 byte and long is 8 byte in my system.在我的系统中,char 的大小是 1 个字节,float 是 4 个字节,long 是 8 个字节。

struct record{
    char name[50];
    float cost;
    long num;
}stu;

Size: 64.

This result in size of: 64结果大小为:64

struct record{
    char name[50];
    long num;
    float cost;
}stu;

Size: 72.尺码:72。

I am not sure how padding takes place in both the cases.我不确定在这两种情况下填充是如何发生的。

Padding is used to maintain alignment of types. padding用于维护alignment个类型。 Processors tend to be more efficient if 4-byte types are aligned on addresses divisible by 4, for example.例如,如果 4 字节类型在可被 4 整除的地址上对齐,处理器往往会更高效。

struct record {
    char name[50];  // offset 0 size 50 (type is size 1)
    /* padding 2 bytes here */
    float cost;     // offset 52 (size 4, offset divisible by 4)
    long num;       // offset 56 (size 8, offset divisible by 8)
} stu;              // total 64 (divisible by 8, (min of current packing size or largest member)
struct record {
    char name[50];  // offset 0, size 50
    /* padding 6 bytes here */
    long num;       // offset size 56, size 8, offset divisible by 8
    float cost;     // offset 64, size 4, offset divisible by 4
    /* padding 4 bytes here */
} stu;   // total 72, divisible by 8 (min of current packing size or largest member)

The trailing packing is needed in the case of contiguous arrays of structures to maintain natural alignment of types for each element of the array.在连续 arrays 结构的情况下,需要尾部填充来为数组的每个元素保持自然的 alignment 类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM