Why does a struct consisting of a char, short, and char (in that order), when compiled in C++ with 4-byte packing enabled, come to a 6-byte struct?

后端 未结 3 876
遥遥无期
遥遥无期 2021-01-14 01:37

I thought I understood how C/C++ handled struct member alignment. But I\'m getting strange results for a particular arrangement in Visual Studio 2008 and 2010.

Speci

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 02:06

    From the MSDN documentation for #pragma pack (where n is the value you set):

    The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

    sizeof(short) is two bytes, which is smaller than the packing value of four bytes that you set, so the short member is aligned to a two byte boundary.

    The last char (c2) is padded with an extra byte after it so that when Alignment objects are placed in an array, the short element is still correctly aligned on a two-byte boundary. Array elements are contiguous and there can be no padding between them, so padding must be added to the end of the structure in order to ensure proper alignment in arrays.

提交回复
热议问题