Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The type of each member of the structure usually has a default alignment i.e.each structure member is aligned on a pre-determined boundary. For this reason the padding is performed in the following wiki example:

struct MixedData
{
    char Data1;
    short Data2;
    int Data3;
    char Data4;
};



struct MixedData  /* After compilation in 32-bit x86 machine */
{
    char Data1; /* 1 byte */
    /* 1 byte for the following 'short' to be aligned on a 2 byte boundary 
assuming that the address where structure begins is an even number */
    char Padding1[1];
    short Data2; /* 2 bytes */
    int Data3;  /* 4 bytes - largest structure member */
    char Data4; /* 1 byte */
    char Padding2[3]; /* 3 bytes to make total size of the structure 12 bytes */
};

What is the (practical) reason that alignment should be preserved?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

On many architectures, aligned reads and writes from and to main memory are much faster than their unaligned counterparts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...