Passing Structure to Functions
Similar to simple variables and arrays, the structure variables can also be passed to a function as arguments both by value or reference.
Call by Value
In this method of passing the Structure to Function, a copy of the actual arguments is passed to the function. Therefore, the changes done to the contents of the structures inside the called functions are not reflected back to the calling function.
Example: Demonstration of passing the structure by value to a function
#include<stdio.h> #include<conio.h> struct student { char name[20]; int age; int roll; char class[5]; }; void main() { struct student stud; clrscr(); printf("\n Enter the student data"); printf("\n Name"); fflsuh(stdin); printf("\n Age"); scanf("%d", &stud.age); printf("\n Roll no."); scanf("%d", &stud.roll); fflush(stdin); printf("\n Class"); gets(stud.class); display(stud); // Structure Being Passes by Value getch(); } display (struct student st) { printf("\n Student data is..."); printf("\n Name = %s", st.name); printf("\n Age = %d", st.age); printf("\n Roll no = %d", st.roll); printf("\n Class = %s", st.class); }
Output
Enter the student data
Name: Pawanpreet Singh
Age: 21
Roll No.: 1251
Class: BSC
Student data is...
Name = Pawanpreet Singh
Age = 21
Roll No = 1251
Class = BSC
Free E-Books and Notes
Class by Reference
In this method of passing the Structure to Functions, the address of the actual Structure variable is passed. The address of the Structure variable is obtained with the help of address operator ‘&’.
Thus the changes done to the contents of such a variable inside the function, are reflected back to the calling function. The following program illustrate the usage of call by reference method.
Example: Demonstration of passing the structure by reference to a function
#include<stdio.h> #include<conio.h> struct student { char name[20]; int age; int roll; char class[5]; }; void main() { struct student stud; clrscr(); printf("\n Enter student data"); printf("\n Name"); gets(stud.name); printf("\n Age"); scanf("%d", &stud.age); printf("\n Roll no."); scanf("%d", &stud.roll); fflush(stdin); printf("\n Class"); gets(stud.class); display(&stud); getch(); } display (struct student *st) { printf("\n Student data is..."); printf("\n Name = %s", st. -> name); printf("\n Age = %d", st --> age); printf("\n Roll no = %d", st -> roll); printf("\n Class = %s", st -> class); }