Home > OS >  How can unions store mutliple values in one memory address in C?
How can unions store mutliple values in one memory address in C?

Time:11-09

The union keyword in C confuses me. From what I have read, unions are used to store different types of data at the same memory address. How can one memory address store different amounts of data. For example,

union Data {
   int i;
   float f;
   char str[20];
};

The memory occupied from this struct is 20 bytes. How can the int, float and char array hold values all at once in the same memory address?

CodePudding user response:

How can unions store mutliple values in one memory address in C?

They cannot and they don't. Only one of the union members is stored at any one time.

Example:

union Data d = {.i = 42}; // d contains only i
printf("%d\n", d.i);
d.f = 3.145f;             // d contains only f
printf("%f\n", d.f);

CodePudding user response:

The different members of a union all refer to the same memory address, Now, a variable of a union type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., the same memory location, can be used to store multiple types of data.

When a variable is associated with a union, the compiler allocates the memory equals to the size of the largest member which is an array of characters of size 20 here so (20 bytes).

CodePudding user response:

A union only stores one thing at any given time - your union type can store either an int or a float or a string.

Enough space is set aside to store the largest member (in this case, the char array), subject to any alignment restrictions. If you do something like

union Data x;
x.i = 10;
x.f = 20.0;
strcpy( x.str, "vootie" );

then the only thing that's actually stored in x is the string "vootie" - the value of i was overwritten when you wrote to f, and the value of f was overwritten when you wrote to str.

CodePudding user response:

Unions do not store many values at the same location, only one. But in C you can access another union member reading (or writing) the same location. It is called union punning

union 
{
    unsigned u;
    float f;
    unsigned char uc[sizeof(float)];
}u;


int main(void)
{
    if(sizeof(u.f) == sizeof(u.u))
    {
        u.f = 1.2345f;

        printf("float value %f is representd as: 0x%x or bytes: 0xhhx 0xhhx 0xhhx 0xhhx ", 
                u.f, u.u, u.uc[0], u.uc[1], u.uc[2], u.uc[3]);
    }
}

https://godbolt.org/z/zqbMvj6cz

  •  Tags:  
  • c
  • Related