sizeof union larger than expected. How does type alignment take place here?

后端 未结 3 1970
别那么骄傲
别那么骄傲 2020-12-02 02:15
#include 

union u1 {
    struct {
        int *i;
    } s1;
    struct {
        int i, j;
    } s2;
};

union u2 {
    struct {
        int *i, j;
          


        
3条回答
  •  囚心锁ツ
    2020-12-02 02:31

    That's because the compiler needs to keep the entire struct (as well as the union) aligned to 8 bytes - due to the fact that you have a pointer inside. (which is 8-bytes in your case)

    So even though you add only 4 bytes with the extra int, struct-alignment forces everything to be aligned to 8 bytes - hence the +8 to bring the total size to 16 bytes.

    The result of this is that:

    struct {
        int *i, j;
    } s1;
    

    has a size of 16 bytes. Since a union must be at least as large as the largest element, it is also forced up to 16.

    http://en.wikipedia.org/wiki/Data_structure_alignment

提交回复
热议问题