Why isn't the size of union the size of the largest member? [duplicate]
Asked Answered
A

1

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.

Anderlecht answered 1/11, 2020 at 17:38 Comment(0)
R
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.

Retainer answered 1/11, 2020 at 17:39 Comment(1)
There can also be other ABI requirements, e.g. in ARM OABI with gcc, struct s { char x[2]; } has size 4.Odyssey

© 2022 - 2024 — McMap. All rights reserved.