How to pass entire structure as an argument to function in C language?

CServer Side ProgrammingProgramming

Passing entire structure as an argument to function −

  • Name of the structure variable is given as argument in function call.

  • It is collected in another structure variable in function header.

Disadvantage

A copy of the entire structure is created again wasting memory

Program

Following program demonstrates passing an entire structure as an argument to function −

 Live Demo

#include<stdio.h>
//Declaring structure//
struct add{
   int var1;
   int var2;
}a;
//Declaring and returning Function//
void show(struct add a){
   //Declaring sum variable//
   int sum;
   //Arithmetic Operation//
   sum=a.var1+a.var2;
   //Printing O/p//
   printf("Added value is %d",sum);
}
void main(){
   //Declaring structure//
   struct add a;
   //Reading User I/p//
   printf("Enter variable 1 = ");
   scanf("%d",&a.var1);
   printf("Enter variable 2 = ");
   scanf("%d",&a.var2);
   //Calling function//
   show(a);
}

Output

Enter variable 1 = 30
Enter variable 2 = 40
Added value is 70
raja
Published on 09-Mar-2021 08:00:25
Advertisements