Why isn't the size of union the size of the largest member?

Viewed 176
union data {
    double number2;
    char name[20];
};

int main() {

  printf("%i\n", sizeof(union data));

  return 0;
}

I expected it to be 20 because it is the largest, but the result is 24.

1 Answers

Besides the size of the largest member, the union must also consider the alignment of the member with the strictest alignment requirements. double must be aligned on 8-byte boundary, so the union must have size that's a multiple of 8. Otherwise in an array of data, some instances of number2 would be misaligned.

Related