Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does union U look like in the memory?

Tags:

c++

unions

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??

like image 516
cplusplusNewbie Avatar asked Oct 15 '25 03:10

cplusplusNewbie


1 Answers

  1. the size of the union is the size of the largest thing in the union.
  2. the layout of the union is whatever you last stored.

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.

like image 74
bmargulies Avatar answered Oct 19 '25 13:10

bmargulies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!