Posted by yanib on 2025-03-22 09:25:14 |
Share: Facebook | Twitter | Whatsapp | Linkedin Visits: 501
In C, structure and union are user-defined data types that allow grouping variables of different data types under a single name. However, they work differently in memory allocation.
struct)A structure is a collection of variables (members) of different types grouped together.
Each member has its own memory location.
The total memory occupied by a structure is the sum of the memory sizes of all its members.
If char[20] takes 20 bytes, int takes 4 bytes, and float takes 4 bytes, then total memory used = 28 bytes.
union)A union is similar to a structure, but all members share the same memory.
The memory allocated to a union is equal to the size of its largest member.
Only one member can store a value at a time.
If int takes 4 bytes, float takes 4 bytes, and char takes 1 byte, then the memory allocated = 4 bytes (size of the largest member).
| Feature | Structure (struct) | Union (union) |
|---|---|---|
| Memory Allocation | Each member gets separate memory | All members share the same memory |
| Size | Sum of sizes of all members | Size of the largest member |
| Access | All members can be accessed at once | Only one member can hold a value at a time |
| Example Use | Storing multiple values together | Saving memory when only one value is needed at a time |
Use struct when you need to store multiple values at the same time.
Use union when you need to save memory and only one value is used at a time.