C Structure vs Union – Key Differences
In C programming, structures and unions are user-defined data types that group different variables under one name. While they seem similar, they differ in how they handle memory and store values.
๐ฆ Structure
A structure allocates separate memory for each member. All members can hold values independently.
๐ Example: Structure
#include <stdio.h> struct MyStruct { int i; float f; char ch; }; int main() { struct MyStruct s = {10, 3.14, 'A'}; printf("Integer: %d\n", s.i); printf("Float: %.2f\n", s.f); printf("Character: %c\n", s.ch); return 0; }
๐ก Union
A union allocates one shared memory for all members. Only one member can contain a valid value at any time, as all members overlap in memory.
๐ Example: Union
#include <stdio.h> union MyUnion { int i; float f; char ch; }; int main() { union MyUnion u; u.i = 10; printf("Integer: %d\n", u.i); u.f = 3.14; printf("Float: %.2f\n", u.f); u.ch = 'A'; printf("Character: %c\n", u.ch); // Notice how previous values get overwritten printf("After char, integer: %d\n", u.i); return 0; }
๐ Structure vs Union Comparison
Feature | Structure | Union |
---|---|---|
Memory Allocation | Each member has separate memory | All members share the same memory |
Access | All members can be accessed at once | Only one member can be used at a time |
Size | Sum of sizes of all members | Size of the largest member |
Use Case | General-purpose grouping of variables | Memory-efficient representation |
๐ฏ Practice Tip
Use structures when you need all data available at once. Use unions when you need to save memory and only one variable is active at a time. Try modifying the examples to see memory behavior in action!