We pass various variables to functions like int, float etc. When we have to work with a lot of data at once then we use structures. Today we will learn how to pass a structure variable as a function argument.
Why Importent?
If you need to store some student data like name, roll, and marks etc together then we will use structure through which it is very easy to insert and print data you don’t have to print data one by one you can pass the entire function. This makes the code readable, memory efficient and much less
How do Pass?
Passing a structure as an argument is very easy. If you have read about functions before, you will know how to pass variables in the same way. While declaring the function, we will specify the type and name of that structure as parameters.
Example:
We have declared a Student structure and created a function called printStudentInto that takes a Student type variable and prints its value.
//Including necessary header file
#include
#include
//Define a structure named 'Student'
struct Student{
char name[50];
int roll;
float marks;
};
//Function prototype (Declaration)
//This function takes a structure variable of type 'struct Student' as an argument.
void printStudentInfo(struct Student stu);
int main(){
//Declare a structure variable s1
struct Student s1;
//Assigning value to the structure members
strcpy(s1.name, "Tapas Mondal");
s1.roll = 136;
s1.marks = 85.5;
//calling the function 'printStudentInfo'
//We are passing the entire structure variable's1' as an argument
//This is know as "Pass by value". A compy of 's1' is sent to the function.
printStudentInfo(s1);
return 0;
}
//function definition
//This function receives a copy of the structure variable passed from main()
void printStudentInfo(struct Student stu){
//printing the details of the student
printf("Student Details:\n");
printf("Name: %s\n",stu.name);
printf("Roll: %d\n",stu.roll);
printf("Marks: %.2f\n",stu.marks);
}
Explain Code
1. Sturcture Declaration
struct Student{
char name[50];
int roll;
float marks;
}
name, roll, and marks. 2. Function Protoptype
void printStudentInfo(struct Student stu);
printStudentInfo that takes a variable stu of type struct Student as input. 3. in the main function
struct Student s1;
strcpy(s1.name, "Tapas Mondal");
s1.roll = 136;
s1.marks = 85.5;
s1 I created a Student structure variable named and set the values of its members. 4. Function Call
printStudentInfo(s1);
printStudentInfo function and passed the variable s1 as an argument. The important thing here is that it is a pass-by-value, meaning the value of s1 is copied to stu. If we change any value in stu, s1 will not change. 5. Function Definition
void printStudentInfo(struct Student stu){
printf("Student Details:\n");
printf("Name: %s\n",stu.name);
printf("Roll: %d\n",stu.roll);
printf("Marks: %.2f\n",stu.marks);
}
stu of type struct Student and prints the values of its members. Output
Student Details:
Name: Tapas Mondal
Roll: 136
Marks: 85.50
