Filling in the union is present or not

Hello to all,
I want to know if a connection uses a connection?
since the union size is the largest data element size, can there be padding at the end?

+7
source share
2 answers

since the size of the union is the largest data element size

This is not necessarily the case. Consider

union Pad { char arr[sizeof (double) + 1]; double d; }; 

The largest member of this association is arr . But, as a rule, a double will be aligned in a multiple of four or eight bytes (depending on the architecture and size of the double ). On some architectures, this is even necessary, since they do not support non-primary readings at all.

So, sizeof (union Pad) usually larger than sizeof (double) + 1 [usually 16 = 2 * sizeof (double) on 64-bit systems and 16 or 12 on 32-bit systems (on a 32-bit system with 8-bit char and 64-bit double , for alignment for double can be only four bytes)].

This means that there should be an addition in the union that can only be placed at the end.

Typically, the size of a union will be the smallest multiple of the greatest alignment required by any member that is not less than the largest member.

+14
source

Union when we use it with primitive types

 union { char c; int x; } 

It doesn't seem to use indentation, because the largest size data is aligned anyway.

But when we embed a structure within a union, it does.

  union u { struct ss { char s; int v; }xx; }xu; 

This led to size 8.

therefore, the answer to your question PADDING is present in UNION.

-3
source

All Articles