Structures in C

In this tutorial, you will learn to construct a user-defined data type called struct in C. You will cover how to define, declare, and access structure and structure members. Additionally, you will grasp the concept of nested structures and the use of keyword typedef in structures with the help of simple and easy examples. 

In C, frequently used tokens like int, the float is the built-in data type. But there is a provision for constructing user-defined data types in C, called custom data type. The structure is a useful weapon in creating these data types.

How to define Structure in C?

A structure is a user-defined data type made of single or multiple data types and each structure has a specific name. The data elements or attributes in a structure are termed as members. 

The basic difference between an array and a structure is that all elements of an array need to be of the same data type. Whereas structure can contain different data types and that is why structure is always preferred over an array.

Syntax:

The prototype of the declaration is


struct struct_name
{
    data_type member_1;
    data_type member_2;
    ...
    ...
    data_type member_n;
};
 

where, struct is a keyword that informs the compiler that a structure is defined in the program. struct_name represents the name of the structure which is used to declare the elementary variable of this particular structure type. member_1 , member_2 ,..., member_n are structure members of the same or different data types. Structure members must be declared inside curly braces {} and should terminate by a semi colon(;). Last but not least the structure definition must end with a semicolon soon after the closing brace. Here is the example of structure definition:


struct employee  
{  
 int id_no;  
   char name[20];  
   float salary;  
};
 

Here we have defined a structure called employee with three members id_no , name and salary. Another important point to be noted is that defining a structure does not reserve any memory space until it is being declared. So a structure and its members become active only when we declare a variable of the structure type. Let’s see how to create a structure variable in C.

How to declare structure variables

To work with a structure we need to create variables for them such that in memory some space will be allocated for the structure. This can be done in two ways:

  1. Using the structure definition 

    
    struct struct_name
    {
        data_type member_1;
        data_type member_2;
        ...
        ...
        data_type member_n;
    } var_1, var_2;
    
     
    

    Here is the example:

    
    struct employee  
    {  
     int id_no;  
       char name[20];  
       float salary;  
    } emp_1,emp_2;  
    
     
    
  2. Using the keyword struct inside main() function

    
    struct struct_name var_1,var_2;
     
    

    Here is the example:

    
    int main()
    {
       struct employee emp_1,emp_2;
    }
    
     
    

In both instances, we have declared two variables emp_1 and emp_2.

Memory allocation of structure variable

Now let's have a look at the memory allocation of structure in C. It is important to understand the fact that the compiler will reserve space for structure in the memory only after the variable declaration. The order of memory reserved follows the order in which the structure members are defined. So in our instance, we have 3 structure members(id_no, name,salary) for each variable (emp_1 and emp_2). The memory allocation can be visualized as follows for easy understanding
 

Key Features of C

From the figure, it is evident that the size of the structure employee is 28 bytes of memory.

How to access Structure members?

To access each element of the structure, we have to use the dot operator(.) or membership operator.The prototype is 


var_1.member_1;
var_1.member_2;
 

Example


emp1. id_no;
emp2.name;
 

How to initialize Structure Member

we can initialize values to the structure variables in two different ways.

  1. Using using curly braces

    
    struct struct_name
    {
        data_type member_1;
        data_type member_2;
        ...
        ...
        data_type member_n;
    }var_1 = {value for member_1, value for member_2,...},
     var_2 = {value for memeber_1, value for member _2,.};
    
    
     
    

    Here is the example:

    
    struct employee  
    {  
     int id_no;  
       char name[20];  
       float salary;  
    }emp_1={1001,"Tom",5000};
    
     
    
     
    
  2. Using dot operator

    
    var_1.member_1 =value;
    var_1.member_2 = value;
     
    

    Here is the example:

    
    emp_2.id_no = 1002;
    emp_2.salary = 6000.00;
     
    

C Structure Example

Given below is a simple program demonstrating the definition, declaration and initialization of structure and structure members..


#include<stdio.h>
#include<string.h>
struct employee
{
    int id_no;
    char name[20];
    float salary;
}emp_1={1001,"Tom",5000};

int main()
{
    struct employee emp_2;

    strcpy(emp_2.name,"Jerry");
    emp_2.id_no = 1002;
    emp_2.salary = 6000.00;

    printf("Employee 1 Details\n");
    printf("Name:%s\n",emp_1.name);
    printf("ID Number:%d\n",emp_1.id_no);
    printf("Salary:%f\n\n",emp_1.salary);

    printf("Employee 2 Details\n");
    printf("Name:%s\n",emp_2.name);
    printf("ID Number:%d\n",emp_2.id_no);
    printf("Salary:%f\n",emp_2.salary);

    return 0;
}

 

Output:


Employee 1 Details
Name:Tom
ID Number:1001
Salary:5000.000000

Employee 2 Details
Name:Jerry
ID Number:1002
Salary:6000.000000

In this example, you can observe that strcpy() function is used to assign the string value to the string variable rather than using =. From the previous tutorial, we have already learned that it is not possible to equate two string variables in C.

Array of Structures in C

In the above program, we have only stored the details of 2 employees by creating 2 structure variables. But what if we need to store the data of 50 employees? It would be tiresome to create 50 variables for 50 employees. So the best solution that  C enables is  Array of Structure. 

An array of structure can be viewed as a gathering of structure variables. Each structure variable stores the information of different entities. The prototype of the array of structure is as follows:
 


struct struct_name var[n];
 

where n is the number of variables .

Let see how to store datas of 5 employees using array of structures:


int main()
{
    struct employee emp[5];
    int i;


    printf("Enter Data of 5 employees\n");
    for(i=0; i<5;i++)
    {
      printf("Enter Id_no. :");
      scanf("%d", &emp[i].id_no);
      printf("Enter name :");
      scanf("%s",emp[i].name);
      printf("Enter Salary :");
      scanf("%d", &emp[i].salary);
    }

    printf("Record of 5 Employees\n");
    for(i=0; i<5; i++)
    {

      printf("Id_no : %d\t", emp[i].id_no);
      printf("Name : %s\t", emp[i].name);
      printf("Salary. : %d\n", emp[i].salary);
    }
    return 0;

}
 

In this program, you can see we have created a variable called emp for 5 employees as an array. While handling arrays we often use for loop to input and output data. The output of this program will be the data of 5 employees containing their id_no , name and salary.

typedef in Structure

typedef is nothing but a special type of keyword in C. It can't create a new type of variable, but it has the ability to assign a new name to a user-defined or built-in data type.

Syntax:

The declaration syntax of typedef will look like this:


typedef data_type new_name;

We can also create new data types using structure. By the use of typedef, we can change its name, and later we can use this new name for structure variables. Here is an example to enlighten this procedure.


struct universe 
{
        char Earth [5] ;
        char Moon [4] ;
};
typedef struct universe UNV;
UNV u;

 

Here universe is a new structure and right after its declaration, we have given it a new name UNV using the keyword typedef. Now we can use the term UNV instead of 'universe' wherever needed. Here we have defined the variable u by typedef in the last argument. 

Another form of the above statements are:
 


typedef struct 
{
        char Earth [5] ;
        char Moon [4] ;
} universe; 
universe u;
 

Now we will consider a short and simple program citing the use of typedef.


#include <stdio.h>
#include<string.h>
struct universe
{
        char Earth [5] ;
        char Moon [4] ;
};
typedef struct universe UNV;
UNV u;
main()
{
  strcpy(u.Earth,"Blue Planet");
  printf  ("Earth : %s\n", u.Earth) ;
  strcpy(u.Moon,"Fossil Planet");
  printf("Moon : %s\n",u.Moon);
}

Output:


Earth : Blue Planet
Moon : Fossil Planet

Nested Structure in C

Another feature that C enables with structure is nested structure. A structure within another structure is termed a nested structure. Nested structures facilitate the creation of complex data types by declaring one structure inside another structure like we declare other structure members inside a structure. 

The nesting can be done in two ways:

  1. Using Separate Structures

    
    struct structure1
                  {
                         - - - - - - - - - -
                         - - - - - - - - - -
                  };
    
                  struct structure2
                  {
                         - - - - - - - - - -
                         - - - - - - - - - -
                         struct structure1 var;
                  };
    
     
    
  2. Using embedded Structures

    
    struct structure2
                  {
                         - - - - - - - - - -
                         - - - - - - - - - -
    
                  struct structure1
                  {
                         - - - - - - - - - -
                         - - - - - - - - - -
                        
                  }var_structure1;
    }var_structure2;
    
     
    

How to access nested structure members

We can easily access the nested structure members by using a chain of dot operators.


var_structure2.var_structure1.member;
 

For instance, we may need to store the date of birth of an employee entity in a structure. Since this attribute contains subparts like date, month and year we need to define it as another structure and nest it into the employee structure.

Example of Nested structure using separate structures


#include<string.h>
struct DOB
{
    int dd;
    int mm;
    int yy;
};
struct employee
{
    int id_no;
    char name[20];
    struct DOB dob;
};

int main()
{
    struct employee emp;

    emp.id_no=1001;
    strcpy(emp.name,"TOM");
    emp.dob.dd = 17;
    emp.dob.mm = 02;
    emp.dob.yy = 2000;

    printf("Employee Details\n\n");
    printf("Name:%s\n",emp.name);
    printf("ID Number:%d\n",emp.id_no);
    printf("DOB(dd:mm:yyyy):%d-%d-%d\n\n",emp.dob.dd,emp.dob.mm,emp.dob.yy);


    return 0;
}

 

Output:


Employee Details

Name:TOM
ID Number:1001
DOB(dd:mm:yyyy):17-2-2000

This program explains how to nest two separate structures . The two structures defined in this program are DOB and employee. DOB is declared inside the employee and is accessed using the chain of dot operators.

Example of Nested Structure by embedding structure

The same can be implemented using embedded structure by defining and declaring the DOB structure inside the employee structure as given below.The main advantage of this kind of nesting is it reduces the code size However it is not applicable when the depth of nesting is more than two.


#include<stdio.h>
#include<string.h>

struct employee
{
    int id_no;
    char name[20];
    struct DOB
{
    int dd;
    int mm;
    int yy;
}dob;
};

int main()
{
    struct employee emp;

    emp.id_no=1001;
    strcpy(emp.name,"TOM");
    emp.dob.dd = 17;
    emp.dob.mm = 02;
    emp.dob.yy = 2000;

    printf("Employee Details\n\n");
    printf("Name:%s\n",emp.name);
    printf("ID Number:%d\n",emp.id_no);
    printf("DOB(dd:mm:yyyy):%d-%d-%d\n\n",emp.dob.dd,emp.dob.mm,emp.dob.yy);


    return 0;
}

 

Note: Nesting of structures can be done to any extend.