Structure padding and packing

前端 未结 9 1229
太阳男子
太阳男子 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:29

    Padding and packing are just two aspects of the same thing:

    • packing or alignment is the size to which each member is rounded off
    • padding is the extra space added to match the alignment

    In mystruct_A, assuming a default alignment of 4, each member is aligned on a multiple of 4 bytes. Since the size of char is 1, the padding for a and c is 4 - 1 = 3 bytes while no padding is required for int b which is already 4 bytes. It works the same way for mystruct_B.

提交回复
热议问题