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

后端 未结 3 1962
别那么骄傲
别那么骄傲 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

    Since a pointer is 8 bytes on your platform, it most probably also requires an alignment of 8 bytes. So when adding another 4 bytes, the struct cannot just have a size of 12 bytes, in which case the individual elements of say an array of u2s would not be properly aligned at 8 byte boundaries, which is neccessary for the pointer member. So you need to increase its size to the next multiple of 8, which is 16. The additional 4 bytes are just unused/undefined.

提交回复
热议问题