Introduction
In C, structures and unions are compound data types used to group together multiple variables of different types under a single name. Both structures and unions allow you to create custom data types that can hold related pieces of information. However, they have some key differences in how they allocate memory and store data:
Structure:
- Definition: A structure is a composite data type that allows you to group together variables of different types under a single name.
- Memory Allocation: Each member of a structure is allocated its own separate memory space. The total memory allocated for a structure is the sum of the memory required for each member.
- Usage: Structures are commonly used when you need to store related but different types of data. For example, representing a person with a structure that contains members for name, age, and address.
Syntax:
struct Person
{
char name[50];
int age;
float salary;
};
Example:
struct Person {
char name[50];
int age;
float salary;
};
Union:
- Definition: A union is also a composite data type that allows you to group together variables of different types under a single name.
- Memory Allocation: Unlike structures, all members of a union share the same memory space. The memory allocated for a union is the size of its largest member.
- Usage: Unions are used when you need to store only one type of data at a time but want to allocate memory for the largest member to save space. For example, representing a variant data type that can hold an integer, a float, or a string.
Syntax:
union Variant
{
int intValue;
float floatValue;
char stringValue[50];
};