Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

C Structure

What is structure?
Array allow to define type of variables that can hold several data items of the same kind.
Similarly, structure is another user defined data type available in C that allows to combine
data items of different kinds. Structures are used to represent a record. Suppose you want to
keep track of your books in a library. You might want to track the following attributes about
each book −
• Title
• Author
• Subject
• Book ID
Again 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.
Let's look at the first approach in detail.
Structures (also called structs) are a way to group several related variables into one place.
Each variable in the structure is known as a member of the structure. Unlike an array, a
structure can contain many different data types (int, float, char, etc.). Structure in c is a user-
defined data type that enables us to store the collection of different data types. It is a
convenient tool for handling group of logically related data items of different data types
Defining a Structure
struct keyword is used to define the structure. The syntax to define the structure in c is
Syntax Example Example
struct Books
struct structure_name { struct student
{ {
char title[50];
data_type member1; char Name[ ];
char author[50];
data_type member2; int PRN;
char subject[100];
. float grade;
int book_id;
data_type memeberN; };
}; };
The key word struct is used to start the definition of structure. Structure name is also known
as structure tag. Each member definition is a normal variable definition, such as int i; or float
f; or any other valid variable definition. All members of the structure are enclosed in pair of
brackets followed by semicolon.

Declaring structure variable


When a struct, type is defined, no storage or memory is allocated. To allocate memory of a
given structure type and work with it, we need to declare variables. When struct variable is
declared then we can access the member of the structure. Following are the two ways to
declare the structure variable.
1. By struct keyword within main() function- following syntax shows the declaration of
structure variable in main( )
struct struct_name variable_name;
For example the structure of employee is defined as

// The variables e1 and e2 are the struct type variables can be used to access the members of
structure.
2. By declaring a variable at the time of defining the structure.-Structure variables can be
declared at the end of its definition followed by semicolon. Syntax for declaration is
as below.
Syntax Example
struct structure_name struct employee
{ {
data_type member1; int id;
data_type member2; char name[50];
. float salary;
data_type memeberN; }e1,e2;
} vraiable1,variable2; Here e1 and e2 variable contains 3
members that are defined in structure
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.
Memory Map of Structure Variable or Memory Space Allocation
Consider an example of struct employee and struct variable emp.
struct employee
{
int id;
char name[20];
float salary;
}emp;
The following image shows the memory allocation of the structure employee
In above example emp is the variable of type struct employee which has three members int
id, char name of size 10 and float salary. id requires 4 byte, name[10] requires 10 byte and
salary require 4 byte so total space required for emp is 18 bytes.
Initialization of structure
After defining of structure and declaration of structure variables it can be initialized by giving
values to all members of structure at once. Following examples shows the methods of
initialization of structure variable at compile time.
struct student
{
int PRN;
char name[20];
int weight;
float height;
}S1={20,”Shri”,50,165.6};
This assigns PRN 20, name Shri, weight 50 and height 165.5 to student S1. There is one to
one correspondence between members and their initial values. Following example shows the
initialization of structure variables when they are declared in main ( ).
struct student int main( )
{ {
int PRN; struct student
char name[20]; {
int weight; int PRN;
float height; char name[20];
}; int weight;
int main( ) float height;
{ };
struct student S1={20,”Shri”,58,165.6}; struct student S1={20,”Shri”,58,165.6};
struct student S2={30,”Rohit”,50,161.5}; struct student S2={30,”Rohit”,50,161.5};
--- ---
} }
C language does not permit the initialization of individual structure member within definition
or templet of structure. This must be done during the declaration of actual variables. Compile
time initialization of structure variable must have following elements.
1. The keyword struct.
2. Structure tag name.
3. Name of the variable to be declared.
4. Assignment operator
5. A set of values for the members of the structure variable, separated by commas, and
enclosed in braces.
6. Terminating semicolon.
Rules for initializing structure
1. Individual element of the structure can not be initialized inside the structure template.
2. The order of values enclosed in the brackets must match the order of the structure in
the structure definition.
3. Partial initialization is permitted. We can initialize only the first few members and
leave the remaining blank. The uninitialized members should be at the end of the list.
4. The uninitialized members will be assigned default values as zero for int and float
type members and ‘/0’ for character type variable.

Accessing Structure Members


1. By . (member or dot operator)
2. By -> (structure pointer operator)
The members of the structure are not variables themselves. They should be linked to the
structure variables in order to make them meaningful members. To access any member of a
structure, we use the member access operator (.) The member access operator is coded as a
period between the structure variable name and the structure member that we wish to access.
Following syntax is used to access the structure member.

structure_variable_name.structure_member
Following code shows how to access the structure members.
/*Write a program to
-Define the structure employee having member’s id, name.
- Initialize the structure for single employee by taking input
- Display the information */
#include<stdio.h>
#include <string.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
}
/*Output
employee 1 id : 101
employee 1 name : Sonoo Jaiswal*/
/*Write a program to
-Define the structure student having member’s rollno, name, address, marks.
- Initialize the structure for single student by taking input at compile time
- Display the information*/
#include<stdio.h>
struct student
{
int rollno;
char name[20];
char Address[30];
float Marks;
};
int main()
{
struct student S1={2010,"Dayanand Patil","RIT, Islampur",87.60};
printf("Information of student\n");
printf("Roll No of student : %d\n",S1.rollno);
printf("Name of student :%s \n",S1.name);
printf("Address of student : %s\n",S1.Address);
printf("Marks of student : %3.2f \n",S1.Marks);
}
Information of student
Roll No of student : 2010
Name of student :Dayanand Patil
Address of student : RIT, Islampur
Marks of student : 87.60
/* Write a program to
-Define the structure book having members book_id ,title, author, price.
- Initialize the structure for single book by taking input at run time
- Display the information */
#include<stdio.h>
#include<string.h>
int main()
{
struct book
{
int book_id;
char Title[50];
char Author[50];
float price;
};
struct book B1;
printf("Enter the Book information\n");
printf("Title of book - ");
gets(B1.Title);
printf("Author of book - ");
gets(B1.Author);
printf("Book id - ");
scanf("%d",&B1.book_id);
printf("Price of book - ");
scanf("%f",&B1.price);
printf("\nThis is the information of book\n");
printf("Book id - %d\n",B1.book_id);
printf("Title of book - %s\n",B1.Title);
printf("Author of book - %s\n",B1.Author);
printf("Price of book - %f",B1.price);
}
/*Output
Enter the Book information
Title of book - ANSI C
Author of book - E Balguruswami
Book id - 253
Price of book - 563
This is the information of book
Book id - 253
Title of book - ANSI C
Author of book - E Balguruswami
Price of book - 563.000000
/* Write a program to
-Define the structure book having members title, author, price and pages
- Initialize the structure for 2 books by taking input at run time
- Display the information */
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
int price;
int pages;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 information */
strcpy(Book1.title, "ANSI C");
strcpy(Book1.author, "E Balagurusamy");
Book1.price = 250;
Book1.pages=503;
/* book 2 information */
strcpy(Book2.title, "Let us C");
strcpy(Book2.author, "Yashawant Kanitkar");
Book2.price = 530;
Book2.pages=729;
/* Display Book1 info */
printf("Book 1 title : %s\n", Book1.title);
printf("Book 1 author : %s\n", Book1.author);
printf("Book 1 price : %d\n", Book1.price);
printf("Book 1 pages : %d\n", Book1.pages);
/* print Book2 info */
printf("Book 2 title : %s\n", Book2.title);
printf("Book 2 author : %s\n", Book2.author);
printf("Book 2 subject : %d\n", Book2.price);
printf("Book 2 pages : %d\n", Book2.pages);
}
/*OUTPUT
Book 1 title : ANSI C
Book 1 author : E Balagurusamy
Book 1 price : 250
Book 1 pages : 503
Book 2 title : Let us C
Book 2 author : Yashawant Kanitkar
Book 2 subject : 530
Book 2 pages : 729

C Array of Structures
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.
Syntax for declaration of array of structure is
struct struct_name variable_name[size];
Consider a case, where we need to store the data of 100 students. We can declare it by using
the structure as given below.
struct Result struct Result
{ {
char Name[50]; char Name[50];
int PRN; int PRN;
int subject1; int subject1;
int subject2; int subject2;
int subject3 int subject3
float average float average
}; } student[100];
int main( )
{
struct Result student[100];
---
}
Structure array is declared similar to the primary variable array and regular array accessing
method is used to access the individual elements and then member operator to access the
members of array. Following format shows the how members are accessed for array of
structure.
student[0].Name student[1].Name
student[0].PRN student[1].PRN
student[0].subject1 student[1].subject1
student[0].subject2 student[1].subject2
student[0].subject3 student[1].subject3
student[0].average student[1].average
Following example shows how to handle array of structure.
/* Write a program to
- Define structure Cricket_Team having element player_name, age, score_in_ODI.
- Declare and do Initialization the structure for 5 cricketers by taking input at run time
- Display the information of all cricketers.*/
#include<stdio.h>
struct Team
{
char Name[50];
int Age;
int Odiscore;
};
int main()
{
int i;
struct Team cricketers[5];
printf("Enter Records of 5 cricketers");
for(i=0;i<5;i++)
{
printf("\nEnter Name of cricketer:");
scanf("%s",crickters[i].Name);
printf("\nEnter Age of cricketer:");
scanf("%d",&crickters[i].Age);
printf("\nEnter ODI score of cricketer:");
scanf("%d",&crickters[i].Odiscore);
}
printf("\nDisplay Information Cricketers:");
for(i=0;i<5;i++)
{
printf("\nName:%s", cricketers[i].Name);
printf("\nAge:%d", cricketers[i].Age);
printf("\nODI Score:%d", cricketers[i].Odiscore);
}
}
/*OUTPUT
Enter Records of 5 cricketers
Enter Name of cricketer: Rohit
Enter Age of crickter:36
Enter ODI score of crickter:3588
Enter Name of cricketer: VIrat
Enter Age of crickter:37
Enter ODI score of crickter:9854
Enter Name of cricketer: Surya
Enter Age of crickter:24
Enter ODI score of crickter:5231
Enter Name of cricketer: Ajay
Enter Age of crickter:36
Enter ODI score of crickter:5632
Enter Name of cricketer: Ashvin
Enter Age of crickter:37
Enter ODI score of crickter:5233
Display Information Cricketers:
Name: Rohit
Age:36
ODI Score:3588
Name: VIrat
Age:37
ODI Score:9854
Name: Surya
Age:24
ODI Score:5231
Name: Ajay
Age:36
ODI Score:5632
Name: Ashvin
Age:37
ODI Score:5233
/*Write a program to
- Define structure Cricket_Team having element player_name, age, score_in_ODI.
- Declare and do Initialization the structure for 5 cricketers by taking input at run time
- Display the information of all those cricketers those score_in_ODI is >=100.*/
#include<stdio.h>
struct Team
{
char Name[50];
int Age;
int Odiscore;
};
int main()
{
int i;
struct Team cricketers[5];
printf("Enter Records of 5 cricketers");
for(i=0;i<5;i++)
{
printf("\nEnter Name of cricketer:");
scanf("%s",cricketers[i].Name);
printf("\nEnter Age of cricketer:");
scanf("%d",&cricketers[i].Age);
printf("\nEnter ODI acore of cricketer:");
scanf("%d",&cricketers[i].Odiscore);
}
printf("\nDisplay Information Cricketers:");
for(i=0;i<5;i++)
{
if(cricketers[i].Odiscore>=100)
{
printf("\nName:%s",cricketers[i].Name);
printf("\nAge:%d",cricketers[i].Age);
printf("\nODI Score:%d",cricketers[i].Odiscore);
}
}
}
/*Output
Enter Records of 5 cricketers
Enter Name of cricketer: Rohit
Enter Age of crickter:37
Enter ODI score of crickter:235
Enter Name of cricketer: VIrat
Enter Age of crickter:39
Enter ODI score of crickter:251
Enter Name of cricketer: Ravindra
Enter Age of crickter:35
Enter ODI score of crickter:37
Enter Name of cricketer: Mahi
Enter Age of crickter:46
Enter ODI score of crickter:521
Enter Name of cricketer: Ashvin
Enter Age of crickter:40
Enter ODI score of crickter:65
Display Information Cricketers:
Name: Rohit
Age:37
ODI Score:235
Name: VIrat
Age:39
ODI Score:251
Name: Mahi
Age:46
ODI Score:521
/*Write a program to
- Define structure Student having element roolno, name.
- Declare and do Initialization the structure for 5 students by taking input at run time
- Display the information of all students.*/
#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);
}
}
/* Write a program to
- Define structure Student having elements rollno, marks of 3 subjects. Total and
percentage.
- Declare and do Initialization the rollno, marks of 3subjects for 5 students by taking
input at run time
- Calculate display the rollno, percentage of all students. .*/
#include<stdio.h>
struct student
{
int rollno;
int subject1;
int subject2;
int subject3;
int total;
float percentage;
};
int main()
{
int i;
struct student marks[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&marks[i].rollno);
printf("\nEnter marks of subject 1:");
scanf("%d",&marks[i].subject1);
printf("\nEnter marks of subject 2:");
scanf("%d",&marks[i].subject2);
printf("\nEnter marks of subject 3:");
scanf("%d",&marks[i].subject3);
marks[i].total=marks[i].subject1+marks[i].subject2+marks[i].subject3;
marks[i].percentage=marks[i].total/3.0;
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, percentage:%f",marks[i].rollno,marks[i].percentage);
}
}
Write a program to
-Define the structure Student having member’s rollno, name, address, marks.
- Declare and do Initialization of structure for 5 students by taking input at run time
- Display the information each student along with grade i.e pass or fail (marks >= 40
then pass, otherwise fail).*/
#include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[50];
char address[50];
int marks;
};
int main()
{
struct student s[5];
int i;
printf("Enter the information of five students\n");
for(i=0;i<5;i++)
{
printf("Enter the Roll No ");
scanf("%d",&s[i].rollno);
printf("Enter the Name ");
scanf("%s",s[i].name);
printf("Enter the Address ");
scanf("%s",s[i].address);
printf("Enter the marks ");
scanf("%d",&s[i].marks);
}
printf("Grades and the information of students\n");
for(i=0;i<5;i++)
{
if(s[i].marks>=40)
{
printf("student having Roll no %d and name %s is pass\n",s[i].rollno,s[i].name);
}
else
{
printf("student having Roll no %d and name %s is fail\n",s[i].rollno,s[i].name);
}
}
}
/*OUTPUT
Enter the information of five students
Enter the Roll No 22
Enter the Name durva
Enter the Address RIT
Enter the marks 87
Enter the Roll No 23
Enter the Name gani
Enter the Address Sangli
Enter the marks 59
Enter the Roll No 24
Enter the Name Don
Enter the Address Islanpur
Enter the marks 54
Enter the Roll No 25
Enter the Name Pushpa
Enter the Address Satara
Enter the marks 25
Enter the Roll No 26
Enter the Name Bahu
Enter the Address karad
Enter the marks 36
Grades and the information of students
student having Roll no 22 and name durva is pass
student having Roll no 23 and name gani is pass
student having Roll no 24 and name Don is pass
student having Roll no 25 and name Pushpa is fail
student having Roll no 26 and name Bahu is fail
/*Write a program to
-Define the structure Book_store having members book_title, book_author, no_of_copies,
price_per_copy.
- Declare and do Initialization the structure for 5 books
-Find the total price of each book in store based on no_of_copies and price_per_book.
-Also print the total price of all the books in store.*/
#include<stdio.h>
#include<string.h>
struct Book_store
{
char title[30];
char author[50];
int copies;
int price;
int total;
};
int main()
{
struct Book_store B[5];
int i,Total=0;
printf("Enter the information of five students\n");
for(i=0;i<5;i++)
{
printf("Enter the book_title ");
scanf("%s",B[i].title);
printf("Enter the book_author ");
scanf("%s",B[i].author);
printf("Enter the No of copies ");
scanf("%d",&B[i].copies);
printf("Enter the price per copy ");
scanf("%d",&B[i].price);
B[i].total=B[i].copies*B[i].price;
Total=Total+B[i].total;
}
printf("\nTotal cost of all books =%d ",Total);
}
/*Output
Enter the information of five students
Enter the book_title cpp
Enter the book_author b
Enter the No of copies 10
Enter the price per copy 123
Enter the book_title mat
Enter the book_author k
Enter the No of copies 15
Enter the price per copy 100
Enter the book_title p
Enter the book_author sharma
Enter the No of copies 5
Enter the price per copy 150
Enter the book_title che
Enter the book_author agr
Enter the No of copies 6
Enter the price per copy 10
Enter the book_title a
Enter the book_author b
Enter the No of copies 5
Enter the price per copy 10
Total cost of all books =3590
Array within structure.
Arrays can be used as a structure member for any type of data. Following example shows the
array as a member of structure.
struct student
{
int rollno;
int subject[5];
int total;
float percentage;
};
In above example the array member subject contains 5 elements as subject[0] to subject[4].
We can access array members using subscript for example student[1].subject[2]; would refer
marks obtained in third subject by second student.
/* Write a program to
- Define structure result having elements rollno, array of 5 subjects. Total and
percentage.
- Declare and do Initialization the rollno, marks of 5 subjects for 5 students by taking
input at run time
- Calculate and display the rollno, percentage of all students.*/
#include<stdio.h>
struct result
{
int rollno;
int subject[5];
int total;
int percentage;
};
int main()
{
int i,j;
struct result student[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&student[i].rollno);
printf("\nEnter marks of the %d students:",i);
for(j=0;j<5;j++)
{
scanf("%d",&student[i].subject[j]);
}
}
for(i=0;i<5;i++)
{
student[i].total=0;
for(j=0;j<5;j++)
{
student[i].total=student[i].total+student[i].subject[j];
student[i].percentage=student[i].total/5;
}
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, percentage:%d",student[i].rollno,student[i].percentage);
}
}
Pointer to Structure
Pointer is a variable that holds the address of another data variable. The variable may be int,
float, char. In the same way pointer can be defined to point the address of structure.
The structure pointer points to the address of a memory block where the Structure is being
stored. Here starting address of the member variable can be accessed.

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 *pointer_variable
example
struct Employee
struct book
{ {
char Name[30]; char name[50];
char Author[25];
int age;
int pages;
} float salary;
struct book *ptr; }employee_one;
In above example *ptr is pointer to structure
struct Employee *employee_ptr;
book.

After defining the structure pointer, we need to initialize it, as the code is shown:
Initialization of the Structure Pointer
Syntax for initialization is as below.
ptr = &structure_variable;
We can also initialize a Structure Pointer directly during the declaration of a pointer.
struct structure_name *ptr = &structure_variable;
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.
//C Program to demonstrate Structure pointer
/* Write a program to
-Define the structure student having members roll_no , name, branch, batch.
- Define pointer to structure student
- Initialize the structure for single student by taking input at run time
- Display the information using pointer */
#include <stdio.h>
#include <string.h>
struct Student
{
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
struct Student s1;
struct Student * ptr = &s1;
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2023;
printf("Roll Number: %d\n", (*ptr).roll_no);
printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);
}
/*OUTPUT
Roll Number: 27
Name: Kamlesh Joshi
Branch: Computer Science and Engineering
Batch: 2023
/* Program to print the members of a structure using Pointer and Arrow Operators
Write a program to
-Define the structure employee having members name , age, salary, department.
- Define pointer to structure.
- Initialize the structure for single employee by taking input at run time
- Display the members of a structure using Pointer and Arrow Operators */
#include <stdio.h>
struct employee
{
char name[100];
int age;
float salary;
char department[50];
};
int main()
{
struct employee emp, *ptr;
printf("Enter Name, Age, Salary and Department of Employee\n");
scanf("%s%d%f%s",emp.name,&emp.age,&emp.salary,emp.department);
/* Printing structure members using arrow operator */
ptr = &emp;
printf("\nEmployee Details\n");
printf("Name:%s\nAge:%d\n",ptr->name, ptr->age);
printf("Salary=%f\nDept:%s",ptr->salary, ptr->department);
}
/*Output
Enter Name, Age, Salary and Department of Employee
Rohit
43
120000
Computer
Employee Details
Name:Rohit
Age:43
Salary=120000.000000
Dept: Computer

Passing Structure to Function in C Programming


You can pass a structure variable to a function as argument like we pass any other variable to
a function. Structure variable is passed using call by value. We can also pass individual
member of a structure as function argument. There are three methods to pass by which values
of structure can be passed from one function to another.
1. In first method each member of the structure is treated as actual argument of function call
and passed. The actual arguments are then treated like ordinary variables. Following
example shows how to pass the individual members of the function to structure.
/*Demo to pass individual members of Explanation- In this code, structure is
structure to function*/ created to hold the name, roll number, and
/*Write a program to
percentage of the student. The input from the
- Define the structure student having
user is stored in the structure. A function
members name, per, rno.
display() is created, which takes the roll
- Initialize the structure for one student by
number and the percentage of the student as
taking input at run time
the parameter. Using the dot (.) operator,
- Pass members per, rno to function
members of the structure are accessed and
- Display the members per, rno in the user
passed it to the function. This is most
defined function */
elementary method and becomes
unmanageable and inefficient when structure
#include <stdio.h>
struct student size is large.
{ The output of the above code is as follows:
char name[50]; Enter name: Aniket
int per, rno; Enter the roll number: 532
}; Enter percentage: 88
void display(int a, int b);
int main() Displaying information
{ Roll number: 532
struct student s1;
printf("Enter name: "); Percentage: 88
gets(s1.name);
printf("Enter the roll number: ");
scanf("%d",&s1.rno);
printf("Enter percentage: ");
scanf("%d", &s1.per);
display(s1.rno,s1.per);
return 0;
}
void display(int a, int b )
{
printf("\nDisplaying information\n");
printf("Roll number: %d", a);
printf("\nPercentage: %d", b);
}
How to Return Structure from a Function?
Multiple variables in the form of a single structure variable. Can be returned to calling
function. following example shows the how a structure is returned from a function.
/* Return Structure from a Function Demo */ Explanation:
#include<stdio.h> • Created a structure named wage and a
struct wage function named employee().
{ • The structure wage store
char name[50]; the name and wage of an employee.
int rs; • The main() function, calling
}; employee() function.
struct wage employee(); • The called function, i.e.,
int main() the employee(), asks the user to enter
{ the name and wage of an employee,
struct wage e; and it is stored in the structure
e = employee(); named e1.
printf("\nWage details of the employee\n"); • The called function returns the
printf("Name : %s",e.name); structure e1 to the main() function.
printf("\nWage : %d",e.rs); • The structure members from the
return 0; structure returned from the called
} function can be accessed using
struct wage employee() the dot (.) operator.
{ • The structure members are then
struct wage e1; printed in the main() function.
printf("Enter the name of the employee : "); The output of the code is as follows:
scanf("%s",e1.name);
printf("\nEnter the wage : "); Enter the name of the employee :
scanf("%d",&e1.rs); Ramdas
return e1; Enter the wage : 5000
} Wage details of the employee
Name : Ramdas
Wage : 5000
2. The second method involves passing of a copy of the entire structure to the called
function. Since the function is working on the copy of the structure, any changes to
structure members within the function are not reflected in the original structure (in calling
function). It is therefore necessary for the function to return entire structure back to calling
function. All compilers may not support to this method.
Function declaration
Return_type function_name(struct tagName argument_name);
Example
void displayDetails(struct student std);
In the above code we are declaring a function named displayDetail(). The return type of this
function is set to void which means the function will return no value. In the list of parameters,
we have std of struct student type. This means std is a variable of student structure. So, the
function displayDetail() can take any variable of type student structure as argument.
Passing structure variable to function (Function call by value)
To pass a structure variable to a function all we have to do is write the name of the variable
and it will pass a copy of the structure variable.
/*Write a program to take details of 3 students as input and display the same by passing the
structure to a function*/
#include <stdio.h>
struct student
{
char firstname[64];
char lastname[64];
char id[64];
int score;
};
void displayDetail(struct student std); //Function declaration
int main()
{
struct student stdArr[3];
int i;
for (i = 0; i < 3; i++)
{
printf("Enter detail of student %d\n", (i+1));
printf("Enter First Name: ");
scanf("%s", stdArr[i].firstname);
printf("Enter Last Name: ");
scanf("%s", stdArr[i].lastname);
printf("Enter ID: ");
scanf("%s", stdArr[i].id);
printf("Enter Score: ");
scanf("%d", &stdArr[i].score);
}
for (i = 0; i < 3; i++)
{
printf("\nStudent %d Detail:\n", (i+1));
displayDetail(stdArr[i]); //Function call with argument as structure
}
return 0;
}
void displayDetail(struct student std) //Called function definition
{
printf("Firstname: %s\n", std.firstname);
printf("Lastname: %s\n", std.lastname);
printf("ID: %s\n", std.id);
printf("Score: %d\n", std.score);
}
/*Output
Enter detail of student 1
Enter First Name: Sudhir
Enter Last Name: Patil
Enter ID: I21
Enter Score: 77
Enter detail of student 2
Enter First Name: Adarsha
Enter Last Name: Mane
Enter ID: I25
Enter Score: 89
Enter detail of student 3
Enter First Name: Sumit
Enter Last Name: Patil
Enter ID: I26
Enter Score: 85
Student 1 Detail:
Firstname: Sudhir
Lastname: Patil
ID: I21
Score: 77
Student 2 Detail:
Firstname: Adarsha
Lastname: Mane
ID: I25
Score: 89
Student 3 Detail:
Firstname: Sumit
Lastname: Patil
ID: I26
Score: 85
/*Passing structure to function using call by value with global declaration of structure
variable*/
/*Write a program to
- Define the structure student having members name, per, rno.
- Initialize the structure for one student by taking input at run time
- Pass entire structure by call by value method.n
- Display the members in the user defined function */
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
3. Third approach employs pointers to pass the structure as an argument. In this method
address location of structure is passed to the called function. function can access the entire
structure and work on it.
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
/* Write a program to
- Define the structure car having members name, seating capacity, fuel used.
- Initialize the structure for one car by taking input at run time.
- Pass entire structure to function by address
- Display the members in the user defined function */
#include<stdio.h>
struct car
{
char name[20];
int seat;
char fuel[10];
};
void print_struct(struct car *);
int main()
{
struct car tata;
printf("Enter the model name : ");
scanf("%s",tata.name);
printf("\nEnter the seating capacity : ");
scanf("%d",&tata.seat);
printf("\nEnter the fuel type : ");
scanf("%s",tata.fuel);
print_struct(&tata);
return 0;
}
void print_struct(struct car *ptr)
{
printf("\n---Details---\n");
printf("Name: %s\n", ptr->name);
printf("Seat: %d\n", ptr->seat);
printf("Fuel type: %s\n", ptr->fuel);
printf("\n");
}
/*OUTPUT
Enter the model name : Indica
Enter the seating capacity : 5
Enter the fuel type : Diesel
---Details---
Name: Indica
Seat: 5
Fuel type: Diesel.
Explanation
In the above code:
• A structure named car and a function named print_struct() are defined. The
structure stores the model name, seating capacity, and the fuel type of the vehicle.
• In the main() function, we created a structure variable named tata and stored the
values. Later the address of the structure is passed into the print_struct() function,
which prints the details entered by the user.
• The address is passed using the address operator ampersand (&). To access the
pointer members, we use the arrow operator -> operator.
In following program, the whole struct student is passed to another function by address. It
means only the address of the structure is passed to another function. The whole structure
is not passed to another function with all members and their values. So, this structure can
be accessed from called function by its address.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record); //Func declaration with pointer to structure argument
int main()
{
struct student Data;
Data.id=1;
strcpy(Data.name, "Raju");
Data.percentage = 86.5;
func(&Data); //Function call with argument as address of structure
return 0;
}
void func(struct student *record) //Function Definition
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}

Nested Structure
Nested structure in C is nothing but structure within structure. One structure can be declared
inside other structure as we declare structure members inside a structure. Syntax for structure
within structure is as below.
Syntax:
struct name_1
{
member1;
member2;
-----
membern;
struct name_2
{
member_1;
member_2;
.----- .
member_n;
} var1;
} var2;
The member of a nested structure can be accessed using the following syntax:
Variable name of Outer_Structure.Variable name of Nested_Structure.data member to
access
/*Write a program to
o Define main structure- Person having members Name, Age and gender.
o Define Nested structure Address with members City, State and Zipcode.
o Define one nested structure variable and one main structure variable.
o Initialization all members of both structure by taking input at run time
o Display the members for both variables. */
#include<stdio.h>
//Declaring outer and inter structures//
struct Person//Main Structure//
{
char Name[50];
int Age;
char Gender[10];
struct Address//Nested Structure//
{
char City[20];
char State[20];
int Zipcode;
}a;//Nested Structure Variable//
}p;//Main Structure Variable//
int main()
{
//Reading User I/p//
printf("Enter the Name of person ");
scanf("%s",p.Name);
printf("Enter the Age of person ");
scanf("%d",&p.Age);
printf("Enter the Gender of person ");
scanf("%s",p.Gender);
printf("Enter the City of person ");
scanf("%s",p.a.City);
printf("Enter the State of person ");
scanf("%s",p.a.State);
printf("Enter the Zip Code of person ");
scanf("%d",&p.a.Zipcode);
//Printing O/p//
printf("\nDisplay information");
printf("\nThe Name of person is : %s ",p.Name);
printf("\nThe Age of person is : %d",p.Age);
printf("\nThe Gender of person is : %c",p.Gender);
printf("\nThe City of person is : %s",p.a.City);
printf("\nThe State of person is : %s",p.a.State);
printf("\nThe Zip code of person is : %d",p.a.Zipcode);
}
/*Output
Enter the Name of person Rohan
Enter the Age of person 40
Enter the Gender of person Male
Enter the City of person Islampur
Enter the State of person Maharashtra
Enter the Zip Code of person 415409
Display information
The Name of person is : Rohan
The Age of person is : 40
The Gender of person is : x
The City of person is : Islampur
The State of person is : Maharashtra
The Zip code of person is : 415409

You might also like