Overlapping memory in unions
What you'll learn: How a union stores multiple members in the exact same memory location, allowing only one value to exist at a time.
One room, many occupants
In the previous lessons, you learned that a struct is like a house with many rooms: every member gets its own space, and they all live there simultaneously.
A union, however, is like a single hotel room. While many different guests might be registered to use that room, only one guest can be inside at any given moment. If a new guest walks in, the previous one must leave.
In C, this means all members of a union share the same starting memory address. The total size of the union is only as large as its biggest member.
Seeing the overlap in code
When you assign a value to one member of a union, you are writing over the memory used by all the other members. If you try to read a different member immediately after, you won't get a separate piece of data; you’ll get a garbled "reinterpretation" of the first member’s bits.
#include <stdio.h>
union Data Holder {
int wholeNumber;
float decimalNumber;
};
int main() {
union DataHolder u;
u.wholeNumber = 42;
printf("Integer: %d\n", u.wholeNumber);
// This overwrites the memory where 42 was stored
u.decimalNumber = 3.14f;
printf("Decimal: %f\n", u.decimalNumber);
// WARNING: wholeNumber is now corrupted because decimalNumber took its spot
printf("Integer after overwrite: %d\n", u.wholeNumber);
return 0;
}
Why use unions?
You might wonder why we would want to "corrupt" our own data. The primary reason is memory efficiency. If you have a list of items where you know for a fact that an item will only ever be either a whole number or a decimal (but never both), a union saves space.
Instead of allocating memory for two variables, the computer allocates just enough for one. You are telling the compiler: "I want to reuse this specific patch of RAM for different purposes at different times." Just remember: the union doesn't keep track of which member is currently active; that is your responsibility as the programmer.
Key takeaway
A union squashes all its members into the same memory address, meaning writing to one member overwrites the others.