How to pass the individual members as arguments to function using structure elements?

CServer Side ProgrammingProgramming

There are three ways by which the values of structure can be transferred from one function to another. They are as follows −

  • Passing individual members as arguments to function.
  • Passing entire structure as an argument to function.
  • Passing the address of structure as an argument to function.

Now let’s see how to pass an individual member of structure elements as arguments to function.

  • Each member is passed as an argument in the function call.

  • They are collected independently in ordinary variables in function header.

Example

Given below is a C program to demonstrate passing individual arguments of structure to a function −

 Live Demo

#include<stdio.h>
struct date{
   int day;
   int mon;
   int yr;
};
main ( ){
   struct date d= {02,01,2010}; // struct date d;
   display(d.day, d.mon, d.yr);// passing individual mem as argument to function
   getch ( );
}
display(int a, int b, int c){
   printf("day = %d\n", a);
   printf("month = %d\n",b);
   printf("year = %d\n",c);
}

Output

When the above program is executed, it produces the following result −

day = 2
month = 1
year = 2010

Example 2

Consider another example, wherein, a C program to demonstrate passing individual arguments of structure to a function is explained below −

 Live Demo

#include <stdio.h>
#include <string.h>
struct student{
   int id;
   char name[20];
   float percentage;
   char temp;
};
struct student record; // Global declaration of structure
int main(){
   record.id=1;
   strcpy(record.name, "Raju");
   record.percentage = 86.5;
   structure_demo(record.id,record.name,record.percentage);
   return 0;
}
void structure_demo(int id,char name[],float percentage){
   printf(" Id is: %d \n", id);
   printf(" Name is: %s \n", name);
   printf(" Percentage is: %.2f \n",percentage);
}

Output

When the above program is executed, it produces the following result −

Id is: 1
Name is: Raju
Percentage is: 86.5
raja
Published on 11-Mar-2021 14:02:48
Advertisements