CHAPTER- EIGHT
Structures
OVERVIEW
•Defining a structure
•Declaring and Accessing Structure Elements
•Initializing Structure
•Array of Structure
•Array as a member to structure
•Pointer as a member to structure
•Structure as a member to structure
Introduction to Structure
• Structure is a collection of heterogeneous (i.e. of different types) data items which are referenced by a single name.
• Structure is also known as record. A structure is a convenient way of grouping several data items together.
• In C programming language, using structure, we can create and use data types other than the basic or fundamental data types.
These are known as derived data types. Structures are created by using struct keyword.
Declaration of Structure & Structure Variables
Syntax for Declaring Structure:
struct structure_name // also known as tag
{
data_type member1;
data_type member2;
data_type member3;
.
.
data_type memberN;
};
Where structure_name and member can be any valid C identifier, data type can be any valid C data types. Structure name
is also known as tag. When we declare a structure, new data type is defined. After declaring structure, structure variables can
be created by using keyword struct and structure_name.
Syntax for Creating Structure Variables After Declaring Structure:
struct structure_name var1, var2, var3, …., varN;
Example: create structure named student with member name, roll & marks:
struct student // structure declaration
{
char name[30];
int roll;
float marks;
};
In this example, student is name of structure and it has three members, namely, name, roll and marks. Now struct student is
name of new data type which can be used to create new structure variables.
For Example:
struct student s1, s2, s3;
In the above example s1, s2, s3 are structure variables.
Structure variables can also be created at the time of structure declaration.
Syntax for declaring structure variables at the time of structure declaration is:
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
.
.
data_type memberN;
} var1, var2, var3, …., varN;
for example:
struct // structure tag is optional
{
char name[30];
int roll;
float marks;
}s1, s2, s3;// structure variables
Initialization of Structure Variables
Assigning value to the structure variable at the time declaration of structure variable is known as initialization of structure
variables. Structure variables can be initialized by using the notation used for array initialization i.e. using {value 1, value 2, ...,
value N}
Example:
If structure is declared like this:
struct student
{
char name[30];
int roll;
float marks;
};
Then structure variables can be created and initialized like this:
struct student s1 = {“Ram”, 1, 80.5};
struct student s2 = {“Sita”, 2, 60};
struct student s3 = {“Geeta”, 3, 50.5};
Accessing Structure Elements
Individual structure elements can be accessed by using the . (dot) operator along with structure variables.
Syntax for accessing structure variables is:
structure_variable.member_name
Lets take an structure named student, previously declared and initialized:
[Link] gives “Ram”
[Link] gives 1
[Link] gives 80.5
similarly,
[Link] gives “Sita”
[Link] gives 2
[Link] gives 60
C program to illustrate declaration and initialization of structure
#include<stdio.h>
/* Declaration of structure */
struct student
{
char name[30];
int roll;
float marks;
};
int main()
{
/* Declaration and initialization of structure variable */
struct student s1 = {“Ram", 1, 80.5};
printf("Student detail is:\n"); Output:
printf("Name : %s\n", [Link]); Student detail is:
printf("Roll : %d\n", [Link]); Name : Ram
printf("Marks : %f\n", [Link]); Roll : 1
return 0; Marks : 80.500000
}
C program to illustrate reading data in structure variables and displaying the content
#include<stdio.h>
/* Declaration of structure */
struct student
{
char name[30];
int roll;
float marks;
};
int main()
{
struct student s1;
printf("Enter name, roll and marks of student:\n");
scanf("%s%d%f",[Link], &[Link], &[Link]);
printf("Student detail is:\n");
printf("Name : %s\n", [Link]);
printf("Roll : %d\n", [Link]);
printf("Marks : %f\n", [Link]);
return 0;
}
WAP in C Program to find difference between two time periods
#include<stdio.h>
struct time
{
int hr;
int min;
int sec;
} start, stop, diff; if( [Link] < start. min)
int main() {
{ [Link] += 60;
// struct time start, stop, diff; [Link]--;
printf("Enter hours, minutes and seconds of start time: "); }
scanf("%d%d%d", &[Link],&[Link], &[Link]); [Link] = [Link] - [Link];
printf("Enter hours, minutes and seconds of stop time: "); [Link] = [Link] - [Link];
scanf("%d%d%d", &[Link],&[Link], &[Link]); [Link] = [Link] - [Link];
if([Link] < [Link]) printf("Difference = %d : %d : %d", [Link], [Link], [Link]);
{ return 0;
[Link] += 60; }
[Link]--;
}
Array of Structure
• 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.
Struct student struct student stud[2];
{ sizeof(stud[0])=10+2+4=16 bytes
char name[10]; Sizeof(stud[2])= 32 bytes
int roll;
float grade;
};
Stud[1]
Stud[0]
Char name[10] int roll float grade Char name[10] int roll float grade
WAP to create a structure with name and roll number as its member. Take information of 5 students and display it.
#include<stdio.h>
#include <string.h>
struct student
{
int roll;
char name[10]; printf("\nStudent Information List:");
}; for(i=0;i<5;i++)
int main() {
{ printf("\nName:%s\t Rollnumber:%d\n",st[i].name,st[i].roll);
int i; }
struct student st[5]; return 0;
printf("Enter Records of 5 students"); }
for(i=0;i<5;i++)
{
printf("\nEnter Name:");
scanf("%s",st[i].name);
printf("\nEnter Rollno:");
scanf("%d",&st[i].roll);
}
Arrays within structures
• Structures also allow the array of members within it.
Example:
struct student
{
int roll;
float marks[5];
};
struct student s1;
S1 structure variable has its two member. One is roll and other is one dimensional array marks[5]
Program to read roll number of a student and find out the total marks he obtained in 5 subjects. Use
structure with its member roll and marks
#include <stdio.h>
#include <stdlib.h>
struct student
{
int roll;
int marks[5];
};
struct student s1;
int main()
{
int i,total=0;
printf("Enter the roll number of student");
scanf("%d",&[Link]);
printf("Enter marks of 5 subjects");
for(i=0;i<5;i++)
{
printf("marks of subject %d:",i+1);
scanf("%d",&[Link][i]);
total+=[Link][i];
}
printf("\nTotal marks =%d",total);
return 0;
}
Program to read roll number of ‘n’ student and find out the total marks each student obtained in 5 subjects. Use structure with its
member roll and marks
#include <stdio.h>
#include <stdlib.h>
struct student
{
int roll;
int marks[10];
};
struct student s[10];
int main()
{
int i,j,n,total[10];
printf("How many students?");
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("Enter the roll number of student-%d:",i+1);
scanf("%d",&s[i].roll);
total[i]=0; for(i=0;i<n;i++)
for(j=0;j<5;j++) {
{ printf("\nRoll no=%d\tTotal marks =%d\n",s[i].roll,total[i]);
printf("marks of subject %d:",j+1); }
scanf("%d",&s[i].marks[j]); return 0;
total[i]+=s[i].marks[j];
}
}
}
Structure within structure(Nesting of structure)
• C provides us the feature of nesting one structure within another structure , using this, complex data types are created.
• For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the
subparts as street number, city, state, and pin code. Hence, to store the address of the employee, we need to store the address
of the employee into a separate structure and nest the structure address into the structure employee.
• The structure can be nested in the following ways.
By separate structure
By Embedded structure
Creating separate structure
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
Here doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can
use Date structure in many structures.
Embedded Structure
• The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line of codes but it can not be
used in multiple data structures. Consider the following example.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure:
We can access the member of the nested structure by outer_Structure.Nested_Structure.member
as given below:
[Link]
[Link]
[Link]
Example
#include<stdio.h>
struct address
{
char city[20];
int c_code;
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d",[Link], [Link], &[Link].c_code);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nCitycode: %d",[Link],[Link],[Link].c_code);
}
WAP to create a structure “student”containing name,dob,phno as its member. The member dob is further classified by
day,month, year. Read data for each member from user and display it.
#include <stdio.h> printf("Enter student name: ");
// Define the structure for date of birth scanf(" %[^\n]", [Link]);
struct Date { printf("Enter date of birth (DD MM YYYY): ");
int day; scanf("%d %d %d", &[Link], &[Link],
int month; &[Link]);
int year; printf("Enter phone number: ");
}; scanf(" %[^\n]", [Link]);
struct Student { printf("\nStudent Details:\n");
char name[50]; printf("Name: %s\n", [Link]);
struct Date dob; printf("Date of Birth: %02d/%02d/%04d\n", [Link],
[Link], [Link]);
char phno[15];
printf("Phone Number: %s\n", [Link]);
};
return 0;
int main() {
}
struct Student s;
Copying and Comparing Structure Variable
• If person1 and person2 belong to the same structure, then the following statements are valid:
peron1=person2;
person2=person1;
The following statements are not permitted.
person1==person2;
person1!= person2;
C does not permit any logical operations on structure variables.
WAP to store name and percentage obtained in board exam of ‘n’ students. Sort the students according to percentage
and display the result.
#include <stdio.h> for(i=0;i<n;i++)// sorting of structure
#include <stdlib.h> {
int MAX=100; for(j=i+1;j<n;j++)
struct student {
{ if(s[i].percent<s[j].percent)
char name[50]; {
float percent; temp=s[i];
}; s[i]=s[j];
int main() s[j]=temp;
{ }
struct student s[MAX],temp; }
int i,n,j;
printf("Enter no of students"); }
scanf("%d",&n); printf("Name:%s\tpercent:\n");
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
printf("Enter name and percent of a student-%d:",i+1); printf("%s\t%f\n",s[i].name,s[i].percent);
scanf("%s%f",s[i].name,&s[i].percent); }
} return 0;
}
Pointer and Structure
• A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure
known as the structure pointer.
• Complex data structures like Linked lists, trees, graphs, etc. are created with the help of structure pointers.
• The structure pointer tells the address of a structure in memory by pointing the variable to the structure variable.
Example: pointer to structure
#include <stdio.h>
struct point
{
int itmNo;
};
int main()
{
struct point s;
// Initialization of the structure pointer
struct point * ptr = &s;
return 0;
}
Accessing Structure members via pointer
There are two ways to access the members of the structure with the help of a structure pointer:
• With the help of (*) asterisk or indirection operator and (.) dot operator.
• With the help of ( -> ) Arrow operator.
/*Program to access the structure members using the structure pointer with the help of the dot operator*/
#include <stdio.h>
#include <stdlib.h>
struct person
{
int id;
char name[50]; Note: this code may not be supported by IDE.
}; Use Turbo C++ compiler
int main()
{
struct person p,*ptr;
ptr=&p;
printf("Enter name and id");
scanf("%s%d",[Link], &[Link]);
printf("\n name: %s\n roll:%d", (*ptr).name,(*ptr).id);
return 0;
}
/*Program to access the structure members using the structure pointer with the help of the arrow operator*/
#include <stdio.h>
#include <stdlib.h>
struct person
{
int id;
char name[50]; Note: this code may not be supported by IDE.
}; Use Turbo C++ compiler
int main()
{
struct person p,*ptr;
ptr=&p;
printf("Enter name and id");
scanf("%s%d",&ptr->name, &ptr->id);
printf("\n name: %s\n roll:%d", ptr->name,ptr->id);
return 0;
}
/*Program to access the structure members using the structure pointer with the help of the arrow operator*/
#include <stdio.h>
#include <stdlib.h>
struct person
{
int id;
char name[50]; Note: this code may not be supported by IDE.
}; Use Turbo C++ compiler
int main()
{
struct person *ptr;
printf("Enter name and id");
scanf("%s%d",ptr->name, &ptr->id);
printf("\n name: %s\n roll:%d", ptr->name,ptr->id);
return 0;
}
Create a Structure named ITEM with its member as itmName and price. Read the information of ‘n’
items. Sort the items on the basis of price and display using pointer.
// sorting
for(i=0;i<n;i++)
#include<stdio.h> {
#include<conio.h> for(j=i+1;j<n;j++)
struct item{ {
char itmName[50]; if((ptr+i)->price>(ptr+j)->price)
int price; {
}; temp=*(ptr+i);
int main() { *(ptr+i)=*(ptr+j);
struct item temp, *ptr; *(ptr+j)=temp;
int n,i,j; }
printf("how many numbers?"); }
scanf("%d",&n); }
for(i=0;i<n;i++) printf("Item name \t price\n");
{ for(i=0;i<n;i++)
printf("Enter name and price"); {
scanf("%s%d",(ptr+i)->itmName,&(ptr+i)->price); printf("%s\t%d\n",(ptr+i)->itmName,(ptr+i)->price);
} }
getch();
return 0;
}
How to Pass a structure as an argument to the functions?
When passing structures to or from functions in C, it is important to keep in mind that the entire structure
will be copied.
This can be expensive in terms of both time and memory, especially for large structures.
The passing of structure to the function can be done in two ways:.
• Pass by Value: A copy of the structure is passed to the function. Changes made to the structure inside the
function do not affect the original structure.
• Pass by Reference: A pointer to the structure is passed to the function. Changes made to the structure
inside the function affect the original structure.
Example 1: Using Call By Value Method
#include <stdio.h> }
struct car {
char name[30]; int main()
int price; {
}; struct car c = { "Tata", 1021 };
print_car_info(c);
void print_car_info(struct car c) return 0;
{ }
printf("Name : %s", [Link]);
printf("\nPrice : %d\n", [Link]);
Example 2: Using Call By Reference Method
printf("Roll: %d\n", student_obj->roll);
#include <stdio.h> printf("Marks: %f\n", student_obj->marks);
}
struct student { int main()
char name[50]; {
int roll; struct student st1 = { "Aman", 19, 8.5 };
float marks; display(&st1);
}; return 0;
void display(struct student* student_obj) }
{
printf("Name: %s\n", student_obj->name);
How to Return a Structure From functions?
• We can return a structure from a function using the return Keyword.
• To return a structure from a function the return type should be a structure only.
#include <stdio.h> return s;
struct student { }
char name[20]; int main()
int age; {
float marks; struct student s1 = get_student_data();
}; printf("Name: %s\n", [Link]);
struct student get_student_data() printf("Age: %d\n", [Link]);
{ printf("Marks: %.1f\n", [Link]);
struct student s; return 0;
printf("Enter name: "); }
scanf("%s", [Link]);
printf("Enter age: ");
scanf("%d", &[Link]);
printf("Enter marks: ");
scanf("%f", &[Link]);
Create a structure named BOOK with its members name and price. Read information for 5 books. Pass the
structure to the function named SORT which arranges the books in ascending order w.r.t price. Display the
sorted information in the main ().
#include <stdio.h> temp = books[j]; printf("Enter the price of book %d: ",
#include <string.h> books[j] = books[j + 1]; i + 1);
struct BOOK { books[j + 1] = temp; scanf("%f", &books[i].price);
char name[100]; } }
float price; } SORT(books, 5);
}; } printf("\nSorted Books (Ascending
Order by Price):\n");
void SORT(struct BOOK books[], int n) }
for (int i = 0; i < 5; i++)
{
{
struct BOOK temp; int main()
printf("Book %d: Name = %s, Price =
for (int i = 0; i < n ; i++) { %.2f\n", i + 1, books[i].name, books[i].price);
{ struct BOOK books[5]; }
for (int j = 0; j < n - i - 1; j++) for (int i = 0; i < 5; i++) {
{ printf("Enter the name of book %d: return 0;
if (books[j].price > books[j + 1].price) ", i + 1); }
{ scanf(" %[^\n]", books[i].name);
Create a structure Employee containing members as Name , age and salary. Input records of 10
employees. Create a function named SEARCH which accepts search_name and a structure as an
argument. Read a name of employee to search in the structure. If found, display the information of the
employee otherwise display “Employee not found !!!”.
#include <stdio.h> printf("Age: %d\n", emp[i].age); printf("Enter details for Employee %d:\n", i + 1);
#include <string.h> printf("Salary: %.2f\n", printf("Name: ");
struct Employee { emp[i].salary); scanf(" %[^\n]", emp[i].name);
char name[100]; found = 1; printf("Age: ");
int age; break; scanf("%d", &emp[i].age);
float salary; } printf("Salary: ");
}; } scanf("%f", &emp[i].salary);
void SEARCH(char search_name[], if (!found) }
struct Employee emp[], int n) { {
int found = 0; printf("Employee not found !!!\n"); char search_name[100];
for (int i = 0; i < n; i++) } printf("\nEnter the name of the
{ } employee to search: ");
if (strcmp(emp[i].name, search_name) int main() scanf(" %[^\n]", search_name);
== 0) { SEARCH(search_name, emp, 10);
{ struct Employee emp[10];
printf("Employee Found!\n"); for (int i = 0; i < 10; i++) return 0;
printf("Name: %s\n", { }
emp[i].name);
Create a structure Student containing name as char string, roll as integer and address as character string. Use user defined function
READ to read name, roll and address for one person from the user and display the contents in following format within a user defined
function named DISPLAY:
NAME: name
ADDRESS: address
ROLL NO: roll
#include <stdio.h> scanf("%d", &s->roll); int main() {
#include <string.h> printf("Enter student address: "); struct Student s;
struct Student { scanf(" %[^\n]", s->address);
char name[100]; } READ(&s);
int roll; void DISPLAY(const struct Student *s) DISPLAY(&s);
char address[100]; { return 0;
}; printf("\nStudent Details:\n"); }
void READ(struct Student *s) printf("Name: %s\n", s->name);
{ printf("Roll: %d\n", s->roll);
printf("Enter student name: "); printf("Address: %s\n", s->address);
scanf(" %[^\n]", s->name); }
printf("Enter student roll number: ");
Additional Topic: UNION
(Not specified as per the IOE syllabus)
This content is just for your knowledge. It does not carry any questions
in the board exam.
Union
Declaring union is similar to structure.
Although union may contain many members of different types, it can handle only one member at a time.
The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union.
Example:
union student
{
int roll;
float marks;
};
Here, the union student has members roll and marks. The data type of roll is integer which contains 2 bytes in memory and the
data type of marks is float which contains 4 bytes in memory. As all union members share same memory, the compiler
allocates largest memory( i.e, 4 bytes in this case).
Example
#include <stdio.h>
#include <stdlib.h>
union student
{
char name[50];
float marks;
};
int main()
{
union student s1;
printf("Enter name and marks of a student");
scanf("%s%f",[Link],&[Link]);
printf("Name:%s\tMarks:%f",[Link],[Link]);
return 0;
}
Structure vs Union
Similarities:
• Both are user-defined data types used to store data of different types as a single unit.
• Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit
field.
• Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment
must have the same members and member types.
• A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the
same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding
parameter.
• ‘.’ operator is used for accessing members.
• Differences:
Any Queries??