Can C arrays contain padding in between elements?

后端 未结 5 746
长情又很酷
长情又很酷 2020-11-27 19:55

I heard a rumor that, in C, arrays that are contained inside structs may have padding added in between elements of the array. Now obviously, the amount of padding could not

5条回答
  •  囚心锁ツ
    2020-11-27 20:47

    Here's the explanation as to why a structure may need padding between its members or even after its last member, and why an array doesn't:

    Different types might have different alignment requirements. Some types need to be aligned on word boundaries, others on double or even quad word boundaries. To accomplish this, a structure may contain padding bytes between its members. Trailing padding bytes might be needed because the memory location directly ofter a structure must also conform to the structure's alignment requirements, ie if bar is of type struct foo *, then

    (struct foo *)((char *)bar + sizeof(struct foo))
    

    yields a valid pointer to struct foo (ie doesn't fail due to mis-alignment).

    As each 'member' of an array has the same alignment requirement, there's no reason to introduce padding. This holds true for arrays contained in structures as well: If an array's first elment is correctly aligned, so are all following elements.

提交回复
热议问题