Why use structure?
In C, there are cases where we need to store multiple attributes of an entity. It is not
necessary that an entity has all the information of one type only. It can have different
attributes of different data types. For example, an entity Student may have its name
(string), roll number (int), marks (float). To store such type of information regarding
an entity student, we have the following approaches:
o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.
#include<stdio.h>
void main ()
{
char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the students
int roll_numbers[2],i;
float marks[2];
for (i=0;i<3;i++)
{
printf("Enter the name, roll number, and marks of the student %d",i+1);
scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
scanf("%c",&dummy); // enter will be stored into dummy character at each iteration
}
printf("Printing the Student details ...\n");
for (i=0;i<3;i++)
{
printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
}
}
Output
Enter the name, roll number, and marks of the student 1Arun 90 91
Enter the name, roll number, and marks of the student 2Varun 91 56
Enter the name, roll number, and marks of the student 3Sham 89 69
Printing the Student details...
Arun 90 91.000000
Varun 91 56.000000
Sham 89 69.000000
The above program may fulfil our requirement of storing the information of an entity
student. However, the program is very complex, and the complexity increase with the
1
amount of the input. The elements of each of the array are stored contiguously, but all
the arrays may not be stored contiguously in the memory. C provides you with an
additional and simpler approach where you can use a special data structure, i.e.,
structure, in which, you can group all the information of different data type regarding
an entity.
What is Structure
Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. Structures ca;
simulate the use of classes and templates as it can store various information
The struct keyword is used to define the structure. Let's see the syntax to define the
structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define a structure for an entity employee in c.
struct employee
{
int id;
char name[20];
float salary;
};
The following image shows the memory allocation of the structure employee that is
defined in the above example.
2
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the
structure easily. There are two ways to declare structure variable:
1. By struct keyword within main( ) function
2. By declaring a variable at the time of defining the structure.
1st way:
It should be declared within the main function.
struct employee
{
int id;
char name[50];
float salary;
};
Now write given code inside the main( ) function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
2nd way:
struct employee
{
int id;
char name[50];
float salary;
3
}e1,e2;
Which approach is good
If number of variables are not fixed, use the 1st approach. It provides you the
flexibility to declare the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable
in main( ) function.
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at
compile time.
struct Patient
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Example:
#include<stdio.h>
struct Employee
4
char name[50];
int age;
float salary;
};
int main( )
struct Employee e1 = {"John", 32, 4200};
//accessing the values in the variable
printf("Name: %s\n", e1.name);
printf("Age : %d\n", e1.age);
printf("Salary : %f\n", e1.salary);
Structure Pointer
The structure pointer points to the address of a memory block where the Structure is
being stored. Like a pointer that tells the address of another variable of any data type
(int, char, float) in memory. And here, we use a structure pointer which tells the
address of a structure in memory by pointing pointer variable ptr to the structure
variable.
Declare a Structure Pointer
The declaration of a structure pointer is similar to the declaration of the structure
variable. So, we can declare the structure pointer and variable inside and outside of the
main() function. To declare a pointer variable in C, we use the asterisk (*) symbol
before the variable's name.
struct structure_name *ptr;
After defining the structure pointer, we need to initialize it, as the code is shown:
Initialization of the Structure Pointer
ptr = &structure_variable;
5
We can also initialize a Structure Pointer directly during the declaration of a pointer.
struct structure_name *ptr = &structure_variable;
As we can see, a pointer ptr is pointing to the address structure_variable of the
Structure.
Access Structure member using pointer:
There are two ways to access the member of the structure using Structure pointer:
1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.
2. Using arrow ( -> ) operator or membership operator.
Program to access the structure member using structure pointer and the dot operator
Let's consider an example to create a Subject structure and access its members using a
structure pointer that points to the address of the Subject variable in C.
Pointer.c
#include <stdio.h>
// create a structure Subject using the struct keyword
struct Subject
// declare the member of the Course structure
char sub_name[30];
int sub_id;
char sub_duration[50];
char sub_type[50];
};
int main()
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
6
ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub */
strcpy (sub.sub_name, " Computer Science");
sub.sub_id = 1201;
strcpy (sub.sub_duration, "6 Months");
strcpy (sub.sub_type, " Multiple Choice Question");
// print the details of the Subject;
printf (" Subject Name: %s\t ", (*ptr).sub_name);
printf (" \n Subject Id: %d\t ", (*ptr).sub_id);
printf (" \n Duration of the Subject: %s\t ", (*ptr).sub_duration);
printf (" \n Type of the Subject: %s\t ", (*ptr).sub_type);
return 0;
Output:
Subject Name: Computer Science
Subject Id: 1201
Duration of the Subject: 6 Months
In the above program, we have created the Subject structure that contains different
data elements like sub_name (char), sub_id (int), sub_duration (char), and sub_type
(char). In this, the sub is the structure variable, and ptr is the structure pointer variable
that points to the address of the sub variable like ptr = &sub. In this way, each *ptr is
accessing the address of the Subject structure's member.
Program to access the structure member using structure pointer and arrow (->)
operator
Let's consider a program to access the structure members using the pointer and arrow
(->) operator in C.
Pointer2.c
7
#include <stdio.h>
// create Employee structure
struct Employee
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
// define the variables of the Structure with pointers
struct Employee emp1, emp2, *ptr1, *ptr2;
int main( )
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;
printf (" Enter the name of the Employee (emp1): ");
scanf (" %s", &ptr1->name);
printf (" Enter the id of the Employee (emp1): ");
scanf (" %d", &ptr1->id);
printf (" Enter the age of the Employee (emp1): ");
scanf (" %d", &ptr1->age);
8
printf (" Enter the gender of the Employee (emp1): ");
scanf (" %s", &ptr1->gender);
printf (" Enter the city of the Employee (emp1): ");
scanf (" %s", &ptr1->city);
printf (" \n Second Employee: \n");
printf (" Enter the name of the Employee (emp2): ");
scanf (" %s", &ptr2->name);
printf (" Enter the id of the Employee (emp2): ");
scanf (" %d", &ptr2->id);
printf (" Enter the age of the Employee (emp2): ");
scanf (" %d", &ptr2->age);
printf (" Enter the gender of the Employee (emp2): ");
scanf (" %s", &ptr2->gender);
printf (" Enter the city of the Employee (emp2): ");
scanf (" %s", &ptr2->city);
printf ("\n Display the Details of the Employee using Structure Pointer");
printf ("\n Details of the Employee (emp1) \n");
printf(" Name: %s\n", ptr1->name);
printf(" Id: %d\n", ptr1->id);
printf(" Age: %d\n", ptr1->age);
printf(" Gender: %s\n", ptr1->gender);
printf(" City: %s\n", ptr1->city);
printf ("\n Details of the Employee (emp2) \n");
printf(" Name: %s\n", ptr2->name);
9
printf(" Id: %d\n", ptr2->id);
printf(" Age: %d\n", ptr2->age);
printf(" Gender: %s\n", ptr2->gender);
printf(" City: %s\n", ptr2->city);
return 0;
Output:
Enter the name of the Employee (emp1): John
Enter the id of the Employee (emp1): 1099
Enter the age of the Employee (emp1): 28
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): California
Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles
Display the Details of the Employee using Structure Pointer
Details of the Employee (emp1)
Name: John
Id: 1099
Age: 28
Gender: Male
10
City: California
Details of the Employee (emp2) Name: Maria
Id: 1109
Age: 23
Gender: Female
City: Los Angeles
In the above program, we have created an Employee structure containing two
structure variables emp1 and emp2, with the pointer variables *ptr1 and *ptr2. The
structure Employee is having the name, id, age, gender, and city as the member. All
the Employee structure members take their respective values from the user one by one
using the pointer variable and arrow operator that determine their space in memory.
Nesting of structures
Nesting of structures is supported in C programming language. We can declare a
structure variable as member of structure or write one Structure inside another
structure.
There are two ways to define nested structure in C language.
Declaring a Structure Variable as Member of Another Structure
In this approach, we create two structures and include a structure variable as member
variable of another structure.
struct Address
int houseNumber;
char street[100];
char zipCode;
};
struct Employee
char name[100];
11
int age;
float salary;
struct Address address;
} employee;
In above declaration, we have included a variable of structure Address as member of
structure Employee.
Declaring a Structure inside Another Structure
In this approach, we declare a structure inside curly braces of another structure.
struct Employee
char name[100];
int age;
float salary;
struct Address
int houseNumber;
char street[100];
char zipCode;
} address;
} employee;
The normal data members of a structure is accessed by a single dot(.)operator but to
access the member of inner structure we have to use dot operator twice.
Outer_Structure_variable.Inner_Structure_variable.Member
For Example
In above example, we can access zipCode of inner structure as
employee.address.zipCode
C Program to Show Nesting of Structure
12
In below program, we declare a structure "employee" which contains another structure
"address" as member variable.
Example1:
#include <stdio.h>
struct employee
char name[100];
int age;
float salary;
struct address
int houseNumber;
char street[100];
}location;
};
int main()
struct employee employee_one, *ptr;
printf("Enter Name, Age, Salary of Employee\n");
scanf("%s %d %f", &employee_one.name, &employee_one.age,
&employee_one.salary);
printf("Enter House Number and Street of Employee\n");
scanf("%d %s", &employee_one.location.houseNumber,
&employee_one.location.street);
printf("Employee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n House Number : %d\n Street : %s\n",
13
employee_one.name, employee_one.age, employee_one.salary,
employee_one.location.houseNumber, employee_one.location.street);
return 0;
Output
Enter Name, Age, Salary of Employee
Jack 30 1234.5
Enter House Number and Street of Employee
500 Street_One
Employee Details
Name : Jack
Age : 30
Salary = 1234.500000
House Number : 50
Street : Street_One
Example2:
#include <stdio.h>
int main()
struct avg
int sub1, sub2, sub3;
float average;
}avg1;
struct student
14
{
char name[30];
struct avg avg1;
};
struct student stud1;
printf("Enter the Name of the student ");
scanf("%s", stud1.name);
printf("\nEnter the marks of the student ");
scanf("%d %d %d ", &stud1.avg1.sub1, &stud1.avg1.sub2, &stud1.avg1.sub3);
stud1.avg1.average = (stud1.avg1.sub1 + stud1.avg1.sub2 + stud1.avg1.sub3)/3;
printf("\n-------Student Details-------\n ");
printf("%s",stud1.name);
printf("\nsub1 : %d \n sub2 : %d \n sub3 : %d ",stud1.avg1.sub1, stud1.avg1.sub2,
stud1.avg1.sub3);
printf("\nAverage : %f %", stud1.avg1.average);
return 0;
Enter the Name of the student siva
Enter the marks of the student 78 82 80
-------Student Details-------
siva
sub1: 78
sub2: 82
sub3: 80
Average: 80.000000 %
15
Array within Structure
As we know, structure is collection of different data type. Like normal data type, It
can also store an array as well.
Syntax for array within structure
struct struct-name
datatype var1; // normal variable
datatype array [size]; // array variable
----------
----------
datatype varN;
};
struct struct-name obj;
Example for array within structure
struct Student
int Roll;
char Name[25];
int Marks[3]; //Statement 1 : array of marks
int Total;
float Avg;
};
void main()
int i;
16
struct Student S;
printf("\n\nEnter Student Roll : ");
scanf("%d",&S.Roll);
printf("\n\nEnter Student Name : ");
scanf("%s",&S.Name);
S.Total = 0;
for(i=0;i<3;i++)
printf("\n\nEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
S.Avg = S.Total / 3;
printf("\nRoll : %d",S.Roll);
printf("\nName : %s",S.Name);
printf("\nTotal : %d",S.Total);
printf("\nAverage : %f",S.Avg);
Output :
Enter Student Roll : 10
Enter Student Name : Kumar
Enter Marks 1 : 78
Enter Marks 2 : 89
Enter Marks 3 : 56
Roll : 10
Name : Kumar
17
Total : 223
Average : 74.00000
C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by
using the structure as given below.
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printing the details....\n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
18
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we
will have to declare 20 different structure variables and store them one by one. This
will always be tough since we will have to declare a variable every time we add a
student. Remembering the name of all the variables is also a very tricky task.
However, c enables us to declare an array of structures by using which, we can avoid
declaring the different structure variables; instead we can make a collection containing
all the structures that store the information of different entities.
Array of Structures in C
An array of structures in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The array
of structures in C are used to store information about multiple entities of different
data types. The array of structures is also known as the collection of structures.
Initializing Array of Structures
We can also initialize the array of structures using the same syntax as that for
initializing arrays. Let's take an example:
struct car
{
char make[20];
char model[30];
int year;
};
struct car arr_car[2] = {
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};
Example:
19
#include<stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
20
Rollno:4, Name:James
Rollno:5, Name:Sarfra
Structure as Function Arguments
We can pass a structure as a function argument just like we pass any other variable or
an array as a function argument.
#include<stdio.h>
struct Student
char name[10];
int roll;
};
void show(struct Student st);
void main()
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
void show(struct Student st)
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
21
Advantages of structure
Here are pros/benefits for using structure:
Structures gather more than one piece of data about the same subject together
in the same place.
It is helpful when you want to gather the data of similar data types and
parameters like first name, last name, etc.
It is very easy to maintain as we can represent the whole record by using a
single name.
In structure, we can pass complete set of records to any function using a single
parameter.
You can use an array of structure to store more records with similar types.
Disadvantages of structure
Here are cons/drawbacks for using structure:
If the complexity of IT project goes beyond the limit, it becomes hard to
manage.
Change of one data structure in a code necessitates changes at many other
places. Therefore, the changes become hard to track.
Structure is slower because it requires storage space for all the data.
You can retrieve any member at a time in structure whereas you can access one
member at a time in the union.
Structure occupies space for each and every member written in inner
parameters while union occupies space for a member having the highest size
written in inner parameters.
22