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

标签 c structure padding

谁能告诉我为什么下面显示的结构的大小是 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文章了解更多详情。

关于c - 假设我们有结构填充且 int 的大小为 4,double 的大小为 8 字节,下面这段代码中结构的大小是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806650/

相关文章:

c - 如何在 vector 中保存结构并用C语言打印出这些值?

html - 我调用哪个元素来提供填充或边距,以便底部有空间

java - java中的密码填充字符串是什么

css - 按钮填充太大

c - 宏作为宏参数扩展不起作用

c++ - gnu缩进的谷歌c风格设置?

c - 如何在不覆盖c中的struct的情况下附加元素

c - 难以理解指针输出

c - 为什么我的 BST 根指针由于某些未知原因而改变?

在 R 中按所需顺序重新排列数据框的列