假设我们有结构填充且 int 的大小为 4,double 的大小为 8 字节,下面这段代码中结构的大小是多少

What is the size of the structure in this code below assuming that we have structure padding and size of int is 4 and size of double is 8 bytes

谁能告诉我为什么下面显示的结构的大小是 24 而不是 20。

typedef struct
{
    double d;  // this would be 8 bytes
    char c;   // This should be 4 bytes considering 3 bytes padding
    int a;   // This would be 4 bytes
    float b; // This would be 4 bytes
} abc_t;

main()
{
    abc_t temp;
    printf("The size of struct is %d\n",sizeof(temp));
}

我的假设是,当我们考虑填充时,结构的大小为 20,但当我 运行 此代码的大小打印为 24。

大小为 24。这是因为最后一个成员填充了所需的字节数,因此结构的总大小应该是任何结构成员的最大对齐 的倍数。

所以填充就像

typedef struct
{
    double d;  // This would be 8 bytes
    char c;    // This should be 4 bytes considering 3 bytes padding
    int a;     // This would be 4 bytes
    float b;   // Last member of structure. Largest alignment is 8.  
               // This would be 8 bytes to make the size multiple of 8 
} abc_t;

阅读 wiki 文章了解更多详情。

也许 packed 属性会回答问题。

typedef struct
{
    double d;  // this would be 8 bytes
    char c;   // This should be 4 bytes considering 3 bytes padding
    int a;   // This would be 4 bytes
    float b; // This would be 4 bytes
} __attribute__((packed)) abc_t ;