Passing Array of Structure to Function in C Programming
- Array of Structure can be passed to function as a Parameter.
- function can also return Structure as return type.
- Structure can be passed as follow
Live Example :
#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
//-------------------------------------
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
//-------------------------------------
void main()
{
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
Explanation :
- Inside main structure and size of structure array is passed.
- When reference (i.e ampersand) is not specified in main , so this passing is simple pass by value.
- Elements can be accessed by using dot [.] operator
About the author: Pritesh View all posts by Pritesh
My name is Pritesh Taral. I am working in well known MNC. as Java Developer. I am part time blogger loves writing articles on C/C++.
I am active on facebook using community fan page .One can Visit me @ Facebook
Facebook Fan Page