Why padding are added, if char comes after int?

后端 未结 4 638
醉酒成梦
醉酒成梦 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:22

    If one is going to have an array of structures, all elements within the array must have the same size and alignment; this would imply that for things in an array the size must be a multiple of alignment. The only time it would be useful to have a structure whose size was not a multiple of alignment would be if it was not incorporated directly into another array, but was instead used as part of another structure. That kind of situation does occur sometimes, but not sufficiently often as to merit special attention in the language design.

提交回复
热议问题