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 915
遥遥无期
遥遥无期 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:08

    Apparently, you indeed misunderstand it. In Visual Studio you cannot increase the alignment requirements for struct members of any type by using the struct packing settings. You can only decrease them.

    If your struct consists of char (aligned at 1 byte boundary) and short (aligned at 2 byte boundary) objects, then using 4- and 8-byte packing settings will have absolutely no effect on the layout or size of your structure. The result will be exactly the same as with 2-byte packing. The structure will have size of 6 bytes.

    The only packing setting that will have any effect in this case is 1-byte packing setting which will decrease the alignment requirement of short from 2 to 1 and result in 4 byte size of the structure.

提交回复
热议问题