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.
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.
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.
© 2022 - 2024 — McMap. All rights reserved.
struct s { char x[2]; }
has size 4. – Odyssey