How is a structure different from a union in terms of memory allocation?

In C, both structures and union are used to group different data types together into a single unit. However, the way memory is allocated for these two types differs significantly.

Structure

In a structure, each member of the structure is allocated its own memory space, and the total size of the structure is the sum of the sizes of its individual members. Each member can store its own value independently, and they each have their own memory location. This means that all members of a structure exist simultaneously and occupy separate memory locations. For Example:

struct Person {
    int age;
    float height;
};

In this case, if age is an int (4 bytes) and height is a float (4 bytes), the structure will use 8 bytes of memory (with possible padding for alignment). The memory is allocated separately for each member.

Union

In a union, all members share the same memory location. A union can only hold the value of one of its members at a time. The size of a union is determined by the size of its largest member, as all members overlap in the same memory space. Therefore, only one member’s data is stored at any given time, and updating one member will overwrite the value of the others. For Example:

union Data {
    int i;
    float f;
    char c;
};

In this case, the union will use the largest memory size of its members. If int takes 4 bytes, float takes 4 bytes, and char takes 1 byte, the union will take 4 bytes of memory, shared by i, f, and c.

Key Difference

  • Structure: Each member gets its own memory space, and the total size is the sum of the sizes of all members.
  • Union: All members share the same memory space, and the total size is the size of the largest member.

In summary, structures allow independent storage for each member, while unions are more memory-efficient, allowing only one member to be stored at a time.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top