Course contentsShow
← C
Lesson 654 of 1,2199. Structures and UnionsFree lesson

Memory layout of a union

Memory layout of a union

What you'll learn: Understand how a union overlaps its members to save space by using a single memory address for multiple data types.

The Shared Room Analogy

Imagine a single bedroom in a house. This room can be used by a guest, or it can be used as a home office, or it can be used for storage. However, it cannot be all three at the exact same time. If you put a desk in there, the guest bed has to go.

In C, a struct is like a suite where every member gets their own private room. A union, however, is that single shared room. All members of a union share the same starting memory address.

Overlapping Memory

Because every member starts at the same spot, a union is only as large as its largest member. If you have a union with a small char (1 byte) and a large double (8 bytes), the entire union will take up 8 bytes of memory.

When you write a value to one member, it overwrites whatever was there previously because they are physically occupying the same "dirt" in your RAM.

Visualizing the Layout

Let’s look at how this looks in code and how the compiler handles the size:

#include <stdio.h>

union Data Holder {
    int i;          // 4 bytes
    char c;         // 1 byte
    float f;        // 4 bytes
};

int main() {
    union DataHolder box;

    // All three of these will print the exact same memory address
    printf("Address of i: %p\n", (void*)&box.i);
    printf("Address of c: %p\n", (void*)&box.c);
    printf("Address of f: %p\n", (void*)&box.f);

    // The size is 4 bytes (the size of the largest member), not 9 bytes
    printf("Total size: %zu bytes\n", sizeof(box));

    return 0;
}

Why use this layout?

This layout is incredibly efficient when you have a variable that needs to hold different types of data at different times, but never at once. By overlapping the memory, you ensure that you aren't wasting space on "empty rooms."

Just remember: since they share the same space, changing the float will scramble the int. You are responsible for keeping track of which member is currently "occupying" the memory.

Key takeaway

A union allocates only enough memory for its largest member, and every member starts at the same memory address.