If I declare a Union as:
union TestUnion
{
struct
{
unsigned int Num;
unsigned char Name[5];
}TestStruct;
unsigned char Total[7];
};
First, sizeof(int)
on most architectures nowadays is going to be 4. If you want 2 you should look at short
, or int16_t
in the stdint.h
header in C99 if you want to be specific.
Second, C uses padding bytes to make sure each struct
is aligned to a word-boundary (4). So your struct looks like this:
+---+---+---+---+---+---+---+---+---+---+---+---+
| Num | N a m e | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+
There's 3 bytes at the end. Otherwise, the next struct
in an array would have it's Num
field in an awkwardly-aligned place, which would make it less efficient to access.
Third, the sizeof
a union is going to be the sizeof
it's largest member. Even if all that space isn't used, sizeof
is going to return the largest result.
You need, as other answers have mentioned, some other way (like an enum
) to determine which field of your union is used.