Like other variables, we can also pass individual
members of a structure and whole structure also ( structure variable).
First, let us see how to pass individual members of a
structure.
Program 1 : Passing individual
members of a structure to a function
#include<stdio.h>
//structure
declaration
struct
student{
int rollno;
float marks;
};
int
display(int roll, float mrk){
printf("\nRoll no : %d\tMarks :
%.2f\n\n",roll,mrk);
}
int
main(){
struct student s;
s.rollno=123;
s.marks=95.5;
display(s.rollno,s.marks);
return 0;
}
Output:
Roll
no : 123 Marks : 95.50
Program 2 : Passing structure
variable to a function : Call by Value
#include<stdio.h>
//structure
declaration
struct
student{
int rollno;
float marks;
};
int
display(struct student ss){
printf("\nRoll no : %d\tMarks :
%.2f\n\n",ss.rollno,ss.marks);
}
int
main(){
struct student s;
s.rollno=123;
s.marks=95.5;
display(s);
return 0;
}
Output:
Roll
no : 123 Marks : 95.50
Program 3 : Passing structure
variable to a function : Call by Reference
#include<stdio.h>
//structure
declaration
struct
student{
int rollno;
float marks;
};
int
display(struct student *ss){
printf("\nRoll no : %d\tMarks :
%.2f\n\n",ss->rollno,ss->marks);
}
int
main(){
struct student s;
s.rollno=123;
s.marks=95.5;
display(&s);
return 0;
}
Output:
Roll
no : 123 Marks : 95.50
Note
that when accessing structure members by pointer to a structure, we ->(arrow
operator) not dot(.) operator.
You may also like:
Structure in C
Typedef in C with examples
Array of Structures in C with Example
Self Referential Structures in C
No comments:
Post a Comment