5
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.

timrau
  • 22,578
  • 4
  • 51
  • 64

1 Answers1

12

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.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • There can also be other ABI requirements, e.g. in ARM OABI with gcc, `struct s { char x[2]; }` has size 4. – M.M Nov 02 '20 at 00:45