Structures and functions in C programming; Through this tutorial, you will learn how to pass struct variables as arguments to a function. And as well as learn how to return struct from a function with the help of examples.
Structures and Functions
- Passing Structure Members To Functions in C Program
- Passing The Entire Structure To Functions in C Program
Passing Structure Members To Functions in C Program
See the following c program to pass structures to a function; as shown below:
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
printf("Enter name: ");
// read string input from the user until \n is entered
// \n is discarded
scanf("%[^\n]%*c", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s) {
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
Passing The Entire Structure To Functions in C Program
See the following c program to pass entire structures to a functions; as shown below:
#include <stdio.h>
//structures declaration
typedef struct {
int a, b;
int c;
}sum;
void add(sum) ; //function declaration with struct type sum
int main()
{
sum s1;
printf("Enter the value of a : ");
scanf("%d",&s1.a);
printf("\nEnter the value of b : ");
scanf("%d",&s1.b);
add(s1); //passing entire structure as an argument to function
return 0;
}
//Function Definition
void add(sum s)
{
int sum1;
sum1 = s.a + s.b;
printf("\nThe sum of two values are :%d ", sum1);
}
Wo its amazing to get your website. Thanks for sharing.