Size of a union vs size of a struct
What you'll learn: How the memory footprint of a union differs from a struct and why unions are the "minimalists" of C programming.
The Suitcase vs. The Locker
To understand memory size, imagine you are packing for a trip.
A struct is like a specialized suitcase with separate compartments for your shoes, your shirts, and your toiletries. If your shoes take up 2 units of space and your shirts take up 4, you need a suitcase that is at least 6 units big. In a struct, every member gets its own private address in memory, and they all live side-by-side simultaneously.
A union is like a single-compartment gym locker. You can store your shoes in there, OR your shirt, but not both at the same time. Because the locker only needs to hold the largest single item you own, its size is determined by that one largest member.
Comparing the Bytes
In C, the sizeof operator reveals this difference clearly. A struct’s size is roughly the sum of its members, while a union’s size is simply the size of its largest member.
#include <stdio.h>
struct DataStruct {
char a; // 1 byte
int b; // 4 bytes
double c; // 8 bytes
};
union DataUnion {
char a; // 1 byte
int b; // 4 bytes
double c; // 8 bytes
};
int main() {
// A struct is large enough to hold ALL members
// Size is approx 1 + 4 + 8 = 13 (usually 16 due to padding)
printf("Struct size: %zu bytes\n", sizeof(struct DataStruct));
// A union is only as large as its BIGGEST member
// Size is exactly 8 (the size of the double)
printf("Union size: %zu bytes\n", sizeof(union DataUnion));
return 0;
}
Why does this matter?
Unions are remarkably memory-efficient. If you have a list of a million items, and each item could be either a small ID number or a long decimal coordinate—but never both—using a union instead of a struct can cut your memory usage in half. The computer simply reuses the same physical space for whichever variable is currently active.
Note that the compiler might add a tiny bit of "padding" (empty space) to both structs and unions to keep memory aligned, but the fundamental rule remains: structs grow with their members, while unions stay as small as their largest member.
Key takeaway
A struct’s size is the sum of all its parts, while a union’s size is only as large as its biggest member.