![]() |
VOOZH | about |
In C programming, both structures and unions are used to group different types of data under a single name, but they behave in different ways. The main difference lies in how they store data.
The below table lists the primary differences between the C structures and unions:
Parameter | Structure | Union |
|---|---|---|
Definition | A structure is a user-defined data type that groups different data types into a single entity. | A union is a user-defined data type that allows storing different data types at the same memory location. |
Keyword | The keyword struct is used to define a structure | The keyword union is used to define a union |
| The size is the sum of the sizes of all members, with padding if necessary. | The size is equal to the size of the largest member, with possible padding. |
Memory Allocation | Each member within a structure is allocated unique storage area of location. | Memory allocated is shared by individual members of union. |
Data Overlap | No data overlap as members are independent. | Full data overlap as members shares the same memory. |
Accessing Members | Individual member can be accessed at a time. | Only one member can be accessed at a time. |
A structure in C is a collection of variables, possibly of different types, under a single name. Each member of the structure is allocated its own memory space, and the size of the structure is the sum of the sizes of all its members.
Syntax
struct name {
member1 definition;
member2 definition;
...
memberN definition;
};
Example:
Geek 20 85.50 Size: 60 bytes
Explanation: In this example, we create a structure Student to store a student's name, age, and grade. Each of the members (name, age, grade) is stored in its own separate memory location, and we access them individually. The size is also the size of all members combined plus structure padding.
A union in C is similar to a structure, but with a key difference: all members of a union share the same memory location. This means only one member of the union can store a value at any given time. The size of a union is determined by the size of its largest member.
Syntax:
union name {
member1 definition;
member2 definition;
...
memberN definition;
};
Example:
100 99.99 A Size: 8
Structures and unions are also similar in some aspects listed below: