Difference between structure and union in C - C-Tutorial

Latest

Saturday, 29 October 2016

Difference between structure and union in C

Difference between structure and union


STRUCTURE

UNION
Allocation of memory
Members of structure do not share memory. So A structure need separate memory space for all its members i.e. all the members have unique storage.
A union shares the memory space among its members so no need to allocate memory to all the members. Shared memory space is allocated i.e. equivalent to the size of member having largest memory.
Members access
Members of structure can be accessed individually at any time.
At a time, only one member of union can be accessed.
Keyword
To define Structure, ‘struct’ keyword is used.
To define Union, ‘union’ keyword is used.
Initialization
All members of structure can be initialized.
Only the first member of Union can be initialized.
Size
Size of the structure is > to the sum of the each member’s size.
Size of union is equivalent to the size of the member having largest size.
Syntax
struct struct_name
{
datatype member _1;
datatype member _2;
.................................datatype member_n;
}struct_variable_name;
union union_name
{
datatype member_1;
datatype member_2;
———-
datatype member_n;
}union_variable_name;
Change in Value
Change in the value of one member can not affect the other in structure.
Change in the value of one member can affect the value of other member.

No comments:

Post a Comment