The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure or Union overcome this problem. Structure or Union have used to store the mixed type of data. That is, the Structure or Union is a group of mix data type which are used separately.

Structure

The structure is a user-defined data-type in the data structure that allows the combination of various types of the data-type. It is used to describe a record. It is represented by the struct keyword in the program.

To define the structure, it uses the struct structure_name statement, as shown in syntax.

Syntax

Note: struct structure_name is used to define the name of the structure and data-type member defines the data-type.

Advantages of Structure

  1. It can store different types of the data-type.
  2. It is user-friendly and simple to understand.
  3. It requires less time to write in the program.

Program

Union

The Union is a user-defined data type in the data structure that allows different data types to be stored in the same memory location. It is represented by the union keyword in the program. A union of several members may be defined together, but at any time, only one member can be valued. Union provides an effective way to use the same memory space for multiple purposes.

To define the Union, it uses the union union_name statement, as shown in syntax.

Syntax

Note: union union_name is used to define the name of the Union and data-type member defines the data-type.

Union works like structure while making the program of the Union, union is written instead of struct keyword.

Program

Advantages of Union

  1. It takes the less memory space than the structure.
  2. It is used when two or more data member has to use the same memory place.

Difference between structure and union

Structure Union
It is represented by the struct keyword in the program. It is represented by the union keyword in the program.
In the structure, every member is assigned a separate memory location. In the Union, every member is shared the same memory location.
The memory size of the structure is equal to the sum of the memory size of each data-type member. The memory size of the union is equal to the largest size of all data-type in the union.
It supports a flexible array. It does not support a flexible array.
In the structure, it can be stored multiple values of the different data members at a time. In the union, it can be stored one value at a time.
Syntax  struct structure_name   {     data-type member 1;     data-type member 2;     …     data-type member n;    };   Syntax    union union_name   {     data-type member 1;     data-type member 2;     …     data-type member n;    };  

Pin It on Pinterest

Share This