CS Electrical And Electronics
@cselectricalandelectronics

10 Difference between structure and Union?

All QuestionsCategory: C Language10 Difference between structure and Union?
CS Electrical And Electronics Staff asked 9 months ago

This is a very common question asked in all software interviews. Well, I have made a list of 10 differences between structure and union. 

  1. Memory Allocation:

    • Structure: Allocates memory for all its members independently. Each member has its own memory location.
    • Union: Allocates memory for the largest member only. All members share the same memory location.
  2. Memory Usage:

    • Structure: This can potentially use more memory due to allocating space for each member.
    • Union: Uses memory efficiently since it shares memory among members, using the size of the largest member.
  3. Member Access:

    • Structure: Members can be accessed simultaneously and independently.
    • Union: Only one member can be accessed at a time since they share the same memory location.
  4. Member Initialization:

    • Structure: Each member can be initialized separately.
    • Union: Only one member can be initialized at a time, affecting all members.
  5. Size Calculation:

    • Structure: Size is the sum of the sizes of all its members.
    • Union: Size is equal to the size of the largest member.
  6. Memory Alignment:

    • Structure: Members are aligned according to their natural alignment requirements.
    • Union: Members are not aligned; they all share the same starting memory location.
  7. Memory Overwrite:

    • Structure: Updating one member does not affect other members.
    • Union: Updating one member can overwrite other members if their size overlaps.
  8. Use Case:

    • Structure: Used when different pieces of data need to be stored together and accessed independently.
    • Union: Used when multiple types of data share the same memory location, and only one type is used at a time.
  9. Complexity:

    • Structure: This can be more complex, with various members having different data types.
    • Union: Simplifies memory management when different types of data share a common context.
  10. Default Values:

    • Structure: Members are independent and can have default values for their respective data types.
    • Union: Since memory is shared, setting a default value for one member affects all members.

Remember that the choice between using a structure or a union depends on the specific requirements of your program. If you need to store different types of data in the same memory location and only one type is used at a time, a union might be more suitable. On the other hand, if you need to store multiple independent pieces of data, a structure would be the appropriate choice.
Thank you for watching this video.