Structure padding and packing

前端 未结 9 1221
太阳男子
太阳男子 2020-11-21 05:04

Consider:

struct mystruct_A
{
   char a;
   int b;
   char c;
} x;

struct mystruct_B
{
   int b;
   char a;
} y;

The sizes of the structur

9条回答
  •  清酒与你
    2020-11-21 05:11

    Structure packing suppresses structure padding, padding used when alignment matters most, packing used when space matters most.

    Some compilers provide #pragma to suppress padding or to make it packed to n number of bytes. Some provide keywords to do this. Generally pragma which is used for modifying structure padding will be in the below format (depends on compiler):

    #pragma pack(n)
    

    For example ARM provides the __packed keyword to suppress structure padding. Go through your compiler manual to learn more about this.

    So a packed structure is a structure without padding.

    Generally packed structures will be used

    • to save space

    • to format a data structure to transmit over network using some protocol (this is not a good practice of course because you need to
      deal with endianness)

提交回复
热议问题