Unions vs. Structures: Key Differences in Memory Management

This article explains the difference between unions and structures in programming, focusing on how they manage memory allocation for variables of different data types. Both structures and unions allow you to group multiple variables, but their memory handling is fundamentally different. Let’s dive in with a practical C example.

Structure Example

struct emp_record {
    char name[10];
    int number[12];
    float Salary;
};


In a structure, memory is allocated contiguously for each member variable. So, `name`, `number`, and `Salary` each get their own dedicated space in memory, one after the other. The total size of the `emp_record` structure will be the **sum** of the sizes of its members (taking into account possible padding for alignment).

## Union Example

```c
union emp_record {
    char name[10];
    int number[12];
    float Salary;
};

In contrast, a union allocates enough memory to hold its largest member. All members of the union share the same memory location. This means only one member of the union can be actively used at any given time. If you assign a value to name, then assign a value to Salary, the value of name will be overwritten.

Memory Allocation: The Core Difference

The fundamental difference lies in how memory is allocated.

  • Structure: Each member gets its own unique memory location. The size of the structure is (roughly) the sum of the sizes of its members.

  • Union: All members share the same memory location. The size of the union is the size of its largest member.

Example Summary

The provided example states that “For structure, total memory allocated is about 7 bytes, which include 1 byte for char,2 for int and 4 for float.” This is incorrect. The sizes depend on the specific compiler and platform. In general:

  • char name[10] would require 10 bytes.
  • int number[12] is also likely to be wrong: It should be a single integer, probably requiring 4 bytes, or an array that requires 12 * sizeof(int) bytes.
  • float Salary would require 4 bytes.

The total size of the struct, assuming int is 4 bytes, would be 10 + 4 + 4 = 18 bytes. However, padding might increase this.

For the union, the memory allocated would be the size of the largest member. If number is incorrectly defined as an array, then the union would require more bytes. If number is a single integer, the union would allocate 10 bytes (for the char array name).

Key Takeaways

  • Structures provide separate memory locations for each member.
  • Unions provide a shared memory location for all members.
  • Use structures when you need to store and access multiple, independent values.
  • Use unions when you need to store one of several possible values, but only one at a time.