C passing array of structure to function



Passing Array of Structure to Function in C Programming

  1. Array of Structure can be passed to function as a Parameter.
  2. function can also return Structure as return type.
  3. 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 :

  1. Inside main structure and size of structure array is passed.
  2. When reference (i.e ampersand)  is not specified in main , so this passing is simple pass by value.
  3. Elements can be accessed by using dot [.] operator