enum Enums { k1, k2, k3, k4 };
union MYUnion {
struct U{
char P;
}u;
struct U0 {
char state;
} u0;
struct U1 {
Enums e;
char c;
int v1;
} u1;
struct U2 {
Enums e;
char c;
int v1;
int v2;
} u2;
struct U3 {
Enums e;
unsigned int i;
char c;
} u3;
struct U4 {
Enums e;
unsigned int i;
char c;
int v1;
} u4;
struct U5 {
Enums e;
unsigned int i;
char c;
int v1;
int v2;
} u5;
} myUnion
I'm so confused with this whole idea of Union in C++. What does this "myUnion" look like in memory?? I know that the data share the same memory block, but how? What is the size of "myUnion"? If it is the size of "u5" then how is the data allocated in this block of memory??
So, in your last union, if you store into .i
, and then store into .e
the first byte of the int will be overwritten with the enum value (assuming that sizeof (enum)
is 1 on your environment).
A union is like:
void * p = malloc(sizeof(biggest_item))
Enums *ep = (Enums *)e;
unsigned int * ip = (unsigned int *)p;
char *cp = (char *)p;
Assignments to *ep
, *ip
, and *cp
work just like the union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With