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

时间:2016-10-01 12:34:00

标签: 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。

2 个答案:

答案 0 :(得分:6)

尺寸为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文章了解更多详情。

答案 1 :(得分:-1)

也许打包属性会回答问题。

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 ;