If I declare a Union as:
union TestUnion
{
struct
{
unsigned int Num;
unsigned char Name[5];
}TestStruct;
unsigned char Total[7];
};
Now, How can I know that whether Total[7] is used or TestStruct is used?
I am using C!
I was revisiting unions and structures and this question came to my mind.
"sizeof
" can't be used as both are of same size i.e. 7 bytes. (And Here comes another question)
When I filled only "Total" with a Character 'a' and Tried sizeof(TestUnionInstance)
, it returned 12 (Size of Char is 1 byte, Right?). So I isolated the structure from it and found that Size of Structure is 12 bytes not 5+2=7 bytes.... Strange!!
Anybody can explain??
P.S. I am using Visual Studio 2008.
char
, not before. Strictly speaking an implementation could put padding before it, but then it would also have to put the same amount of padding before it if you changed fromchar [5]
tochar[6]
, which would be pretty nonsensical. C requires structures with a common initial sequence of elements to be compatible. – Crucial