0

I have the following union :

union Variant{
    char txt[10];
    double floating_point;
};

The confusion comes when I try to print sizeof(Variant) , which outputs 16 bytes.

Why doesn't it output 10 bytes instead of 16 ? if union takes up as much memory as its largest member, it should do max(sizeof(char[10]), sizeof(double)) no ?

Where does the 6 bytes comes from anyway, if in my system a double takes 8 bytes ?

Useless
  • 64,155
  • 6
  • 88
  • 132

2 Answers2

1

Because of the alignment on the 8 bytes boundary, since the size of the union's largest member double is probably 8 bytes on your machine. If you had an int instead of double, the size would probably be 12.

The size of your char array is 10 bytes, because it has ten elements. Which is greater than your largest member double size, which is 8. So, the next possible alignment is 2 * 8 which is 16.

If your array had 8 elements or less, the size of the union would be 8, etc.

Ron
  • 14,674
  • 4
  • 34
  • 47
0

Why doesn't it output 10 bytes instead of 16 ? if union takes up as much mamory as its largest member, it should do max(sizeof(char[10]), sizeof(double)) no ?

The size of a structure or a class is a multiple of the alignment of a member with the largest alignment requirement. Here, that member is double, whose alignment is 8, i.e. alignof(double) == 8 and alignof(Variant) == alignof(double).

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271