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

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

    The struct u2.s2 is 16 bytes because of alignment constraints. The compiler is guaranteeing that if you make an array of such structs, each pointer will be aligned on an 8-byte boundary. The field *i takes 8 bytes, then j takes 4 bytes, and the compiler inserts 4 bytes of padding. Because the struct is 16 bytes, the union containing it is also 16 bytes.

提交回复
热议问题