What is Structures and Unions in C Language with Free Notes

Structures

Till now we have used the derived data type i.e. array, which is preferred method of storing homogeneous (similar type) elements. SO the elements of an array must be of some data type. In certain situations, we require a construct that can store data items of mixed data types. C supports Structures for this purpose.

The basic concepts of a Structures comes from day to day life. We observe that certain items are made up of components of different types e.g. a date is composed of three parts: day, month and year as shown in fig.

Similarly the information about a student is composed of many components like name, age, roll no., class etc.

Free E-Books

The collective information about the student as shown is called a Structure. it is similar to a record. The term structure can be precisely defined as: A group of related data items of arbitrary types. Each member of a Structure is a variable that can be referred to through the name of the structure.

Unions

Like Structures Unions are also of derived data type. Both Structures and unions are used to contain members or variables of different type in a single unit.

While Structures are used to store different members at different places in memory, a union is used to store different members at same memory location. Thus unions are used to conserve memory.

In union memory assignment is the largest member of union whereas in structures, the memory reserved ix the total sum of memories to be used by all the members of structure.

The general form of union declaration is: –

union<name>
{
   member1;
   member2;
   :
   member n;
};
union name var1, var2, ..., var n;

OR

union<name>
{
   member1;
   member2;
   :
   member n;
};
var1, var2, ..., var n;

Where union is a required keyword, <name> is the name of the union and is optional, member 1,2….n are the individual member declarations, var1, var2,… var n are the union variables.

e.g.  union test 
{
  int v1;
  float v2;
  char v3;
}
   t;

In this example a total of 4 bytes reserved in memory because member of float type takes 4 bytes. Which is shown in fig. in which v3 takes 1 byte(char), same byte is shared for v1 which takes 2 bytes(int), these bytes are shared for v2 which takes 4 bytes.

Whereas if it is a structure, total 7 bytes are reserved, 2 for v1, 4 for v2 and 1 for v3.

Accessing Union Members

The union members can be accessed in the same manner as that of Structure member i.e. with the help of dot operator.

The variable of union can be accessed as shown below: –

t.v1 = 10;
t.v2 = 75.75;
t.v3 = 'A';

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top