Posted By:
11 Jun, 2013 12:19 am PDT

Structures and Unions in C and C++

Explain structures and unions and also give examples

Structures are used to combine data items of different kinds while unions are used to store different data types in the same memory location.

Please watch the video for details...

Was it useful?  

Arrays allow us to store data of same kind where as  structures allow us to store data items of various datatype

Defining a structure:

Struct keyword is used to define a structure.

Struct structure_name







Struct book


Char name[15];

Int price;

Int pages;



Here the struct book declares a structure to hold the details of book which consist of three data fields namely name, price, and pages. These fields are called structure elements or members. Each member can have different datatype like in this case name is of “char” type and price is of “int” type etc. Book is the name of structure and is called structure tag.

 Unions are completely similar to structures. Syntax is also the same. But the only difference is in terms of storage. 



Uses of Structures

A structure is a good way of storing related data together. It is also a good way of representing certain types of information. Complex numbers in mathematics inhabit a two dimensional plane (stretching in real and imaginary directions). These could easily be represented here by:

typedef struct {
          double real;
          double imag;
  } complex;


doubles have been used for each field because their range is greater than floats and because the majority of mathematical library functions deal with doubles by default.

In a similar way, structures could be used to hold the locations of points in multi-dimensional space. Mathematicians and engineers might see a storage efficient implementation for sparse arrays here.

Apart from holding data, structures can be used as members of other structures. Arrays of structures are possible, and are a good way of storing lists of data with regular fields, such as databases.

Another possibility is a structure whose fields include pointers to its own type. These can be used to build linked lists, trees or other connected structures.


Was it useful?  

Please login to reply to this problem.