Lesson 13·C Programming

Unions in C

Shared memory allocations and differences with structures

What is a Union?

A Union is a user-defined composite data type in C that allows multiple members of different data types to be stored in the exact same memory location.

The union keyword is used to declare a union. While syntactically similar to structures, the fundamental difference between a structure and a union is 'storage'.

Structure Storage

In a Structure, each member gets its own distinct memory offset. Total size is at least the sum of all members.

Union Storage

In a Union, all members share the exact same starting memory address. Total size is equal to the size of the largest member. Only one member can hold a valid value at any given moment.

C Example
union techno {
    int comp_id;
    char name[20];
    float sal;
} tch;

Shared Memory Allocation Diagram

Illustrating how union members overlap in physical memory:

Union shared memory allocation model
All union members occupy the exact same memory bytes; storing into one member overwrites the others.

Demonstration of Memory Overwriting

Notice how assigning to name corrupts the previous integer value stored in id:

C Example
#include <stdio.h>
#include <string.h>

union techno {
    int id;
    char name[20];
} tch;

void main() {
    tch.id = 101;
    printf("Developer ID before name write: %d\n", tch.id);

    strcpy(tch.name, "Technowell");
    printf("Developer Name: %s\n", tch.name);

    // Reading id after name was written demonstrates garbage/corrupted value
    printf("Developer ID after name write (corrupted): %d\n", tch.id);
}
Program Output
Developer ID before name write: 101
Developer Name: Technowell
Developer ID after name write (corrupted): 1801813332
Note
Because tch.id and tch.name share the same memory bytes, writing "Technowell" directly overwrites the 4 bytes previously holding 101.