What is the Difference Between Structure and Union in C?

🆚 Go to Comparative Table 🆚

The main difference between a structure and a union in C lies in the way they allocate memory and store data. Here are the key differences:

  1. Memory Allocation: In a structure, each member has its distinct storage location, and the total memory allocated is equal to the sum of the memory requirements of all members. In a union, all members share a single memory location, and only one member can be accessed at a time. The memory allocated to a union is equal to the size of its largest member.
  2. Accessing Members: In a structure, you can retrieve any member at a time without affecting other members. In a union, changing the value of one member will affect the others, as they share the same memory location.
  3. Usage: Structures are mainly used for storing various data types under a single unit, while unions are mainly used for storing one value at a time for all its members.
  4. Flexible Arrays: Structures support flexible arrays, while unions do not.

Both structures and unions are user-defined data types in C that allow you to combine different types of data together as a single unit. They can contain various object types, including different structures, unions, arrays, and bit fields.

Comparative Table: Structure vs Union in C

Here is a table comparing the differences between structures and unions in C:

Feature Structure Union
Memory Location Each member has a unique memory location Members share a single memory location
Memory Size Structure takes more storage space as memory is allocated to all data members Union takes only the memory size required by the largest member
Accessing Members Can access multiple members at a time Can access only one member at a time
Flexible Array Support Supports flexible arrays Does not support flexible arrays
Main Purpose Storing various data types Storing one data type at a time

Both structures and unions are user-defined data types in C that allow you to group different data types together. However, they serve distinct purposes and have key differences in terms of memory usage and accessibility.