Why padding are added, if char comes after int?

后端 未结 4 636
醉酒成梦
醉酒成梦 2020-12-03 19:11

For example, there is a structure

struct A
{
char a;
int i;
};

In this case, we have a[1 byte] + padding[3 byte] + int[4 byte] = 8.

4条回答
  •  误落风尘
    2020-12-03 19:40

    The reason the compiler have to add padding at the end of your struct is that the struct can be part of an array, and each element of an array must be properly aligned.

    It seems your platform wants an int to be aligned to 4 bytes.

    If you declare an array of your struct A:

    struct A array[2];
    

    Then the first int member of array[1] should also have an alignment of 4 bytes. So the compiler pads your struct A to be 8 bytes to accomplish that, whilst if it didn't add any padding and sizeof(struct A) were 5 bytes, array[1] would not be properly aligned.

    (Keep in mind that a compiler can't insert padding inbetween array elements, padding have to be part of the array elements themselves since sizeof array must be the same as sizeof(struct A) * 2 in the above case)

提交回复
热议问题