Moule Lin
← All notes

Byte Alignment

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–|