Passing Structure As Paramenter To Function
Passing Structure As Paramenter To Function
int main() {
struct student s;
printf("Enter name: ");
gets(s.name);
printf("Enter the roll number: ");
scanf("%d",&s.rno);
printf("Enter percentage: ");
scanf("%d", &s.per);
display(s);
return 0;
}
void display(struct student s ) {
printf("\nDisplaying information\n");
printf("Roll number: %d", s.rno);
printf("\nPercentage: %d",s.per);
}
Output:
Enter name: Abcd
Enter the roll number: 12
Enter percentage: 100
Displaying information
Roll number: 12
Percentage: 100
2. Passing individual members of structure
Sometimes we don’t want to pass the entire structure to the function. We want to
pass only a few members of the structure. We can use the dot (.) operator to access
the individual members of the structure and pass them to the function. Passing the
entire structure to the function is unnecessary when we want to print only a few
structure members.
#include <stdio.h>
struct student {
char name[50];
int per,rno;
};
void display(int rno , int per);
int main() {
struct student s;
display(s.rno, s.per);
return 0;
}
Passing the parameter as a value will make a copy of the structure variable, passing
it to the function. Making a copy of all the members and passing it to the function
takes a lot of time and consumes a lot of memory. To overcome this problem, we
can pass the address of the structure.
#include <stdio.h>
struct student {
char name[50];
int per,rno;
};
int main() {
struct student s;
struct student * p;
p=&s;
printf("Enter name: ");
gets(s.name);
printf("Enter the roll number: ");
scanf("%d" ,&s.rno);
printf("Enter percentage: ");
scanf("%d", &s.per);
display(p);
return 0;
}
void display(struct student * p ) {
printf("\nDisplaying information\n");
printf("Roll number: %d",p->rno);
printf("\nPercentage: %d",p->per);
}
Output:
Enter name: Abcd
Enter the roll number: 12
Enter percentage: 100
Displaying information
Roll number: 12
Percentage: 100