In order to enable the CPU to efficiently and quickly access variables, the starting address of the variable should have some characteristics, called "alignment". For example, for a 4-byte int type variable, its starting address should be on a 4-byte boundary, where the starting address can be divisible by 4. The alignment rules for variables are as follows (32-bit system): Char aligns on byte boundaries short (16-bit) aligns int and long (32-bit) on a double-byte boundary on a 4-byte boundary to align a double on a 4-byte boundary to align a twin on a 8-byte boundary
The details of byte alignment are related to the specific compiler implementation, but in general, three criteria are met: 1) The first address of a struct variable can be divisible by the size of its widest
base type member; 2) The offset of each member of the struct relative to the first address of the struct is an integer multiple of the member size, if necessary the compiler will Add padding bytes between the members, for example, the address space of the second struct variable above. 3) The total size of the struct is an integer multiple of the size of the structure's widest base type member, and if necessary the compiler will be at the last member The padding bytes are then added. For example: struct S1{ char a; short b; char c;}; In the above structure, size is the largest of short, its length is 2 bytes, so the structure of Char members A, C are aligned in 2 , sizeof (S1) results equal to 6; A & nbsp b CS1 memory layout 1* &NBSP ; 11 1* (* denotes filled bytes, same as below) if changed to struct S1{ char a; int B; char c;}; The result is obviously 12. a &N Bsp . NBSP;CS1 Memory layout 1*** 1111 1*** 2: struct S1{ Char a; &N Bsp Long b; }; struct S2 { Char c; St Ruct S1 d; Long long e; &N Bsp };sizeof (S2) results were 24;
See more complex examples of two struct members: Typedef struct student{ char name[10]; long sno; & nbsp char sex;  FLOAT score [4];} Stu;sizeof (STU) =? Stu Memory Layout name SNO sex &NB Sp score 1111111111** 1111 &N Bsp 1*** 1111111111111111sizeof (STU) =10+2+4+1+3+16 If we change the members in the STU order: typedef struct student{ char name[10]; char sex; long sno;& nbsp  FLOAT score [4];} STU; Stu Memory layout Name sex sno score &NBS P 1111111111 1* 1111 1111111111111111sizeof (STU) =10+2+4+16 Note: 1) for an empty structure, sizeof = = 1; Because each instance of the struct must be guaranteed to have a unique address in memory. 2) The static members of the struct do not size the struct body, because static variables are stored in a location independent of the instance address of the struct. For example: struct {static int I;} T;sizeof (T) = = 1;struct {char A; static int I;} T1;sizeof (T1) = = 1;
Byte alignment issues