Why short is 2-byte aligned?

后端 未结 1 429

here is a declaration of a C struct:

struct align
{
    char c; //1 byte
    short s;//2 bytes
};

On my environment, sizeof(struct align) i

1条回答
  •  走了就别回头了
    2021-01-06 04:01

    That is because a member of a struct is no difference from a single variable of that type, from the machine's perspective. Whatever alignment you choose, it applies to both.

    For example, if short is two-byte long,

    struct align
    {
        char c;
        short s; // two-byte word
    };
    
    short ss; // two-byte word
    

    The member s is of 2-byte type (e.g. WORD in IA32), exactly the same type of a "standalone" variable ss. The underlying architecture regards them as the same. So when there comes to an alignment requirement for that type, it just applies to both.

    And if you add the padding at the end of the data, it may still be misaligned. Consider the start of ss is at the end of a 4-byte boundary.

    0 讨论(0)
提交回复
热议问题