Structures in C Programming
Structures in C Programming
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
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
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;
};
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:
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:
1st way:
struct employee
{
int id;
char name[50];
float salary;
};
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;
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;
};
or
p1.weight = 73;
p1.age = 23;
Example:
#include<stdio.h>
struct Employee
4
char name[50];
int age;
float salary;
};
int main( )
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.
After defining the structure pointer, we need to initialize it, as the code is shown:
ptr = &structure_variable;
5
We can also initialize a Structure Pointer directly during the declaration of a pointer.
There are two ways to access the member of the structure using Structure pointer:
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>
struct Subject
char sub_name[30];
int sub_id;
char sub_duration[50];
char sub_type[50];
};
int main()
sub.sub_id = 1201;
return 0;
Output:
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>
struct Employee
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
int main( )
ptr1 = &emp1;
ptr2 = &emp2;
8
printf (" Enter the gender of the Employee (emp1): ");
printf ("\n Display the Details of the Employee using Structure Pointer");
9
printf(" Id: %d\n", ptr2->id);
return 0;
Output:
Second Employee:
Name: John
Id: 1099
Age: 28
Gender: Male
10
City: California
Id: 1109
Age: 23
Gender: Female
Nesting of structures
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;
} employee;
struct Employee
char name[100];
int age;
float salary;
struct Address
int houseNumber;
char street[100];
char zipCode;
} address;
} employee;
Outer_Structure_variable.Inner_Structure_variable.Member
For Example
In above example, we can access zipCode of inner structure as
employee.address.zipCode
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()
&employee_one.salary);
&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
Jack 30 1234.5
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
float average;
}avg1;
struct student
14
{
char name[30];
};
scanf("%s", stud1.name);
printf("%s",stud1.name);
return 0;
-------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.
struct struct-name
----------
----------
datatype varN;
};
struct Student
int Roll;
char Name[25];
int Total;
float Avg;
};
void main()
int i;
16
struct Student S;
scanf("%d",&S.Roll);
scanf("%s",&S.Name);
S.Total = 0;
for(i=0;i<3;i++)
scanf("%d",&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 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
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
Array of Structures in C
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:
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 main()
printf("\nStudent name:\t");
scanf("%s", std.name);
scanf("%d", &std.roll);
show(std);
21
Advantages of 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.
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
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