C Programming language

adplus-dvertising
Array of structures in C
Previous Home Next

As we are aware of the fact that the structures in the C language provides a mechanism to incorporate different data types within a same structure like integers, floats and character values which are known as structure members. As a fact, structures are simple to  define if there are only one or two elements but in case if too many objects are needed e.g.. to show the data of each student of a class, in that case we introduces the concept of the array of the structures.

We can declare an array of structures as follows :

#include <stdio.h>

struct studentinfo
{
int rollno.;
char name[21];
char sex;
};

studentinfo detail[35];

In the above declaration, we have defined a structure named studentinfo which keeps the information about a particular student like rollno. of the student , name and sex. Then after defining the structure we have declared an array of structures we can contain 35 objects of such structure and can incorporate the details of 35 students.

Initializing the array of structures

An array of structure can initialized in the same manner as we initialize a simple array. It must be kept in mind that only the static and external variables are initialized, lets understand to initialize a array of structure by taking this example :

#include <stdio.h>

 /* we have taken a structure which  stores the information about the information about
 a particular employee */

struct employeeinfo        
{
int emp_id;
char sex;
int salary;
};

 /* here we have declared an array of structure i.e. data which is of employeeinfo type and
 contains the 3 objects of above defined structure i.e. of employeeinfo */
 
employeeinfo data[3] = { {1001, 'M', 10000}, {1002, 'F', 8000}, {1003, 'M', 15000}};        

The above initialized values will be considered or assigned by the compiler in the following manner :

data[0].emp_id = 1001          data[0].sex = 'M'            data[0].salary = 10000

data[1].emp_id = 1002          data[1].sex = 'F'            data[1].salary = 8000

data[2].emp_id = 1003          data[2].sex = 'M'            data[2].salary = 15000

If some of the values of the structures elements are not initialized then they are initialized to a default value of '0'.

For example, if above declared structure is lacking some initialized elements then,

employeeinfo data[3] = { {1001, 'M'}, {1002, 'F'}, {1003, 'M'}};

The above initialized values will be considered or assigned by the compiler in the following manner :

data[0].emp_id = 1001               data[0].sex = 'M'               data[0].salary = 0

data[1].emp_id = 1002               data[1].sex = 'F'                data[1].salary = 0

data[2].emp_id = 1003               data[2].sex = 'M'               data[2].salary =0
      
 
/* where uninitialized element i.e. salary is provided with the default value of zero */

Previous Home Next