Difference Between Structure and Union in C
https://www.computersprofessor.com/2016/05/difference-between-structure-and-union.html?m=0
S.no
|
C Structure
|
C Union
|
1
|
Structure allocates storage space for all its
members separately.
|
Union allocates one common storage space for
all its members.
Union finds that which of its member needs high storage space over other members and allocates that much space |
2
|
Structure occupies higher memory space.
|
Union occupies lower memory space over structure.
|
3
|
We can access all members of structure at a
time.
|
We can access only one member of union at a
time.
|
4
|
Structure example:
struct student { int mark; char name[6]; double average; }; |
Union example:
union student { int mark; char name[6]; double average; }; |
5
|
For above structure, memory allocation will be
like below.
int mark – 2B char name[6] – 6B double average – 8B Total memory allocation = 2+6+8 = 16 Bytes |
For above union, only 8 bytes of memory will
be allocated since double data type will occupy maximum space of memory over
other data types.
Total memory allocation = 8 Bytes |