Think First ⚡
A Memory Saving Challenge!
Suppose you have an item that can be identified by EITHER an int id OR a char name[20]. You will never use both at the same time. If you use a structure, it allocates memory for BOTH. How can we save memory?
💡 Challenge: Store one of many types
Which feature allows multiple variables to share the EXACT SAME memory location?
Pointers
Arrays
Union
Structure
✓ Correct answer! A Union is exactly like a structure, but instead of allocating memory for all members, it allocates memory ONLY for the largest member and shares it!
memory_waste.cUsing Struct
struct Item {
int id; // 4 bytes
char name[20]; // 20 bytes
};
// Total Memory = 24 bytes (or more with padding)
// But we only need ONE of them at a time!
Definition
What is a Union?
A union is a user-defined data type similar to a struct, but all its members share the same memory location. The size of the union is the size of its largest member.
union_example.cHover to explore ✶
union Data {
int i; // 4 bytes
float f; // 4 bytes
char str[20]; // 20 bytes (Largest!)
}; ← Semicolon mandatory!
// Declare union variable
union Data data;
// Memory allocated: 20 bytes total!
data.i = 10;
printf("%d\n", data.i); // OK
strcpy(data.str, "Hello");
printf("%d\n", data.i); // Garbage! 'str' overwrote it.
🧠 Core Memory Rule:
In a union, you can only safely use ONE member at a time. If you write to a new member, the previous member's data is corrupted/overwritten!
Size of Union = Size of Largest Member
Here,
Here,
int is 4, float is 4, char[20] is 20. So the total size of the union is 20 bytes (not 28).
Comparison
Difference Between Union and Structure
Understanding when to use a struct vs a union is crucial. Here is the ultimate comparison.
| Feature | Structure (struct) | Union (union) |
|---|---|---|
| Keyword | struct |
union |
| Memory Allocation | Allocates separate memory for each member. | Allocates single shared memory block equal to the largest member. |
| Total Size | Sum of the sizes of all members (plus padding). | Size of the largest member only. |
| Member Access | All members can be accessed and store data at the same time. | Only ONE member can store valid data at any given time. |
| Value Alteration | Modifying one member does NOT affect the others. | Modifying one member overwrites the others. |
| Best Used For | Grouping related data that exist together (e.g., Student details). | Saving memory when variables are mutually exclusive. |
Knowledge Check ✍
Let's test what you've learned!
Question 1 of 3
Loading...