Skip to content
Related Articles

Related Articles

Difference between Array and Union in C
  • Last Updated : 03 Dec, 2020

1. Array in C :
An array is collection of similar data items accessed by a common name stored at continuous memory locations. The elements of an array can be accessed using indices. They can be used to store primitive data types such as int, float, double, char, etc. but all elements have to be of the same data type. Below is the picturesque representation of an array.

Declaration of an array :

datatype array_name[size]

2. Union in C :
Union is a user defined datatype that allows storage of heterogenous elements in the same memory location. Size of the union is the size of the largest element in the union. Below is the picturesque representation of a union.



Declaration of a union :

union name
{
  datatype element;
  datatype element;
};



Difference between Array and Union :

ARRAY UNION
Collection of elements of same data types. Collection of elements of heterogenous data types.
Arrays can be one or two dimensional. Unions do not have type.
Each element is allocated a specific memory location. The elements share the memory location which has size equivalent to the size of the largest size element of the union.
All members can contain value at a given time. Only one member can contain value at a given time.
Not an efficient use of memory as all members are allocated different memory locations. Efficient use of memory as all members do not require separate memory location.
Array elements can be accessed using index. The elements of a union cannot be accessed using index.

Syntax :

datatype array_name[size]

Syntax :
Union user defined name

{

datatype Variable 1; datatype variable2;

};

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :