Structure memory alignment

How to calculate the size of the structure?

Remember structure alignment rules

1. The first member is at the address at offset 0 from the structure variable.
2. Other member variables should be aligned to an address that is an integer multiple of a number (alignment number).
Alignment = the smaller of the compiler's default alignment and the size of the member. The default value in VS is 8
3. The total size of the structure is an integer multiple of the maximum alignment number (each member variable has an alignment number).
4. If a structure is nested, the nested structure is aligned to an integer multiple of its own maximum alignment number, and the overall size of the structure is an integer of all maximum alignment numbers (including the alignment number of nested structures). times.

struct s
{
  char c1;//根据规则1从0开始     0 + 1 == 1
  int i;//根据规则2对齐,int类型为4,vs为8,较小值为4  1 + 4 == 5
  char c2;//继续根据规则2,char类型为1,vs为8,较小值为1    5 + 1 == 6
          //最后根据规则3,最大对其数为4,0 —— 6 七个字节,因此大小为8字节
};

printf("%d\n", sizeof(struct S1));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324303920&siteId=291194637