- The starting address of a struct variable is divisible by the size of its widest basic-type member;
- The offset of each member relative to the struct's starting address is an integer multiple of the member's size; if necessary, the compiler inserts padding bytes between members (internal padding);
- The total size of the struct is an integer multiple of the size of its widest basic-type member; if necessary, the compiler adds padding bytes after the last member (trailing padding)
For example
struct student
{
char name[5];
int num;
short score;
}
|char|char|char|char|
|char|—-|—-|—-|
|——–int——–|
|–short–|—-|—-|
The data needs only 11 bytes (5+4+2), but because int is 4-byte aligned by default, it is stored at a starting address divisible by 4. That is, if name[5] starts at 0, it occupies 5 bytes, and num starts at byte 8 (offset) (because int is 4 bytes, its starting position must be divisible by 4). So sizeof(student)=16, and a few bytes in between sit idle. This makes it easier for the computer to read and write data quickly; it trades space for time. Its data alignment is shown below:
struct student
{
int num;
char name[5];
short score;
}
num starts at 0, name starts at byte 4 (offset) and takes 5 consecutive bytes, and score starts at byte 10 (offset), so sizeof(student)=12. Its data alignment is shown below:
|——–int——–|
|char|char|char|char|
|char|—-|–short–|