Difference Between Structure and Union in C

Structures and unions are user-defined data types in C that allow grouping of different data types. While they look similar, they differ mainly in memory allocation and usage behavior.

What is a Structure?

A structure is a collection of variables of different data types, where each member has its own separate memory location.

C
// Structure example
#include <stdio.h>

struct Student {
    int id;
    float marks;
};

int main() {
    struct Student s1 = {1, 95.5};
    printf("%d %.1f", s1.id, s1.marks);
    return 0;
}

What is a Union?

A union is a collection of variables where all members share the same memory location. Only one member can hold a value at a time.

C
// Union example
#include <stdio.h>

union Data {
    int i;
    float f;
};

int main() {
    union Data d;
    d.i = 10;
    printf("%d", d.i);
    return 0;
}

Key Differences Between Structure and Union

  • Structure allocates separate memory for each member, union shares memory
  • All structure members can be used simultaneously, only one union member at a time
  • Structure size is sum of all members, union size is size of largest member
  • Structures are used for complex data records, unions for memory optimization
  • Changing one union member affects others

Comparison Table

FeatureStructureUnion
MemorySeparate for each memberShared memory
SizeSum of membersLargest member
UsageAll members usableOne at a time
EfficiencyLess memory efficientMore memory efficient
Example UseRecordsMemory-critical systems

Memory Example

C
// Size comparison
printf("%lu", sizeof(struct Student));
printf("%lu", sizeof(union Data));

When to Use Structure?

  • When all data members are needed
  • For storing records (student, employee)
  • When clarity is important
  • For complex data representation

When to Use Union?

  • When memory optimization is required
  • When only one value is needed at a time
  • In embedded systems
  • For variant data types

Real-World Applications

  • Structures in databases
  • Unions in hardware programming
  • Structures in file systems
  • Unions in memory-constrained systems
  • Both used in system-level programming

Common Mistakes to Avoid

  • Accessing inactive union member
  • Misunderstanding memory sharing
  • Incorrect size assumptions
  • Improper initialization
  • Confusing struct and union usage

Advanced Concepts

  • Nested structures and unions
  • Bit fields
  • Padding and alignment
  • Anonymous unions
  • Tagged unions

Practice Exercises

  • Create struct for employee record
  • Compare struct and union sizes
  • Use union for memory optimization
  • Implement tagged union
  • Explore alignment issues

Conclusion

Structures and unions serve different purposes in C programming. Structures are best for storing complete data sets, while unions are useful when memory efficiency is critical.

Note: Note: Use structures for full data storage and unions when memory saving is required.