Unions

Understanding unions and how they differ from structures. Using unions to save memory.


Unions vs. Structures in C

This lesson explores the key differences between unions and structures in the C programming language. It compares how they allocate memory, how members are accessed, and discusses when to use one over the other, focusing on the core distinction of sharing memory vs. allocating separate memory for each member.

Structures

A structure is a user-defined data type that allows you to group together variables of different data types under a single name. Each member of a structure is allocated its own independent memory space.

Memory Allocation in Structures

In a structure, each member variable is allocated a separate memory location. The total size of a structure is generally the sum of the sizes of its individual members (though padding may be added by the compiler for alignment purposes). This means that you can store values in all the member variables of a structure simultaneously.

Accessing Members in Structures

You access members of a structure using the dot operator (.) when working with a structure variable directly, or the arrow operator (->) when working with a pointer to a structure.

Example of a Structure

 #include <stdio.h>

    struct Person {
        char name[50];
        int age;
        float salary;
    };

    int main() {
        struct Person person1;

        strcpy(person1.name, "John Doe");
        person1.age = 30;
        person1.salary = 50000.0;

        printf("Name: %s\n", person1.name);
        printf("Age: %d\n", person1.age);
        printf("Salary: %.2f\n", person1.salary);

        return 0;
    } 

In this example, person1 has independent memory allocated for name, age, and salary. Changes to one member do not affect the others.

Unions

A union is also a user-defined data type in C. However, unlike structures, a union allows you to store different data types in the same memory location. Only one member of a union can hold a value at any given time.

Memory Allocation in Unions

The memory allocated to a union is equal to the size of its largest member. All the members of the union share the same memory location. When you assign a value to one member, the values of all other members become invalid (or rather, their interpretation becomes nonsensical based on the new data stored at that memory location).

Accessing Members in Unions

Like structures, you access members of a union using the dot operator (.) or the arrow operator (->).

Example of a Union

 #include <stdio.h>

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

    int main() {
        union Data data;

        data.i = 10;
        printf("data.i: %d\n", data.i);

        data.f = 220.5;
        printf("data.f: %.2f\n", data.f);

        data.i = 10; // overwrite the float to int
        printf("data.f: %.2f\n", data.f); //print garbage data.
        printf("data.i: %d\n", data.i);

        strcpy(data.str, "C Programming");
        printf("data.str: %s\n", data.str);

        printf("data.i: %d\n", data.i); //data.i changed because char array is largest.

        return 0;
    } 

In this example, data has memory allocated based on the largest member (str, which is 20 bytes). When you assign a value to data.i, the memory used by data.f and data.str is overwritten (at least in part depending on the size of the members compared to the maximum member).

Key Differences Summarized

FeatureStructureUnion
Memory AllocationEach member has its own independent memory location. Total size is (typically) the sum of member sizes.All members share the same memory location. Size is the size of the largest member.
Simultaneous StorageAll members can store values simultaneously.Only one member can hold a valid value at any given time.
UsageGrouping related data of different types. Representing complex data structures.Conserving memory when only one of several members needs to be stored at any given time. Type punning (though this should be used with caution).

When to Use Which

  • Use a structure when you need to store and access multiple related values of different data types simultaneously. Structures are ideal for representing entities with multiple attributes.
  • Use a union when you need to store only one value from a set of possible data types at a time. Unions are useful for conserving memory or when you need to interpret the same memory location in different ways (type punning). Be careful with type punning and ensure you understand the implications on memory representation.