In C programming, structures help us to store different types of data. And with the help of pointers, we can access and manipulate the memory address of a variable. Today we will learn that we can pass pointers to structures as arguments to functions.
Why do we pass pointers to Structure?
- Memory Efficient:- If we pass a large structure to a function, then a copy of the entire structure will be created. This wastes both memory and time. If we pass only the address, then only the address will be passed, which takes very less space and saves a lot of time.
- Original Data Modify:- If we ever need to change the original data of the structure, we can easily do so by passing the pointer.
Example:
In the code below, I have defined the
Student structure and then passed the pointer to a function to print the data. If you want to modify the original data, you can do so very easily from here.
#include
#include
struct Student{
char name[50];
int roll;
float marks;
};
void printStudent(struct Student *s){
printf("Student Name: %s\n",s->name);
printf("Roll Number: %d\n",s->roll);
printf("Marks: %.2f\n",s->marks);
}
void modifyStudent(struct Student *s){
strcpy(s->name, "Manas Kumar Mondal");
s->roll = 105;
s->marks = 92.5;
}
int main(){
struct Student student1 = {"Tapas Mondal", 136, 85.5};
printf("Before Modification:\n");
printStudent(&student1);
modifyStudent(&student1);
printf("\nAfter Modification:\n");
printStudent(&student1);
return 0;
}
Explain this Code:
1. Header File and Structure Declaration
#include
#include
struct Student{
char name[50];
int roll;
float marks;
};
stdio.handstring.hHeader file added.StudentThere is a structure created in it called:namerollmarks
2.Print Function
void printStudent(struct Student *s){
printf("Student Name: %s\n",s->name);
printf("Roll Number: %d\n",s->roll);
printf("Marks: %.2f\n",s->marks);
}
- This function takes a
Studentstructure pointer and prints the student information.
3.Modify Function
void modifyStudent(struct Student *s){
strcpy(s->name, "Manas Kumar Mondal");
s->roll = 105;
s->marks = 92.5;
}
- This function changes the student information.
- Name changed to “Manas Kumar Mondal”
- Roll changed to “105”
- Marks change to “”92.5
3.Main Function
int main(){
struct Student student1 = {"Tapas Mondal", 136, 85.5};
printf("Before Modification:\n");
printStudent(&student1);
modifyStudent(&student1);
printf("\nAfter Modification:\n");
printStudent(&student1);
return 0;
}
Student1A structure named variable has been created.- Name:
Tapas Mondal - Roll:
136 - Marks:
85.5
Output:
Before Modification:
Student Name: Tapas Mondal
Roll Number: 136
Marks: 85.50
After Modification:
Student Name: Manas Kumar Mondal
Roll Number: 105
Marks: 92.50
