Just like any other variables that are passed in a function, structure can also be pas structs to functions. But before that you must go through the following topics in C.
Passing structures to functions
While passing a structure we may pass the members of the structure or we can pass the structure variable itself. See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <stdio.h> struct student { char name[50]; int roll; }; // function prototype void display_function(struct student stud); int main() { struct student s1; printf("Enter Student's name: "); scanf("%[^\n]%*c", s1.name);//reads until \n is entered printf("Enter the Student's Roll: "); scanf("%d", &s1.roll); display_function(s1); //struct variable is passed return 0; } void display_function(struct student stud) { printf("\n-------------DISPLAY---------\n"); printf("Name of the Student: %s", stud.name); printf("\nRoll Number of the Student: %d", stud.roll); } |
Output:
1 2 3 4 5 6 | Enter Student's name: Sherlock Holmes Enter the Student's Roll: 101 -------------DISPLAY--------- Name of the Student: Sherlock Holmes Roll Number of the Student: 101 |
The variable of the structure (s1
) itself is passed into the display_function
function as an argument.
How to return a struct from a function
Go through the following example to see how a structure is returned from the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <stdio.h> struct student { char name[25]; int roll; }; // struct type function prototype struct student stud_detail(); int main() { struct student s; s1 = stud_detail(); printf("\n---------DISPLAY--------\n"); printf("Name of the Student: %s", s1.name); printf("\nRoll of the Student: %d", s1.roll); return 0; } struct student stud_detail() { struct student s; printf("Enter Student's name: "); scanf ("%[^\n]%*c", s.name); printf("Enter Roll Number: "); scanf("%d", &s.roll); return s;// returning struct variable } |
Output:
1 2 3 4 5 6 | Enter Student's name: Sherlock Holmes Enter Roll Number: 101 ---------DISPLAY-------- Name of the Student: Sherlock Holmes Roll of the Student: 101 |
As you can see in the example, a separate structure variable (s
) is declared inside the function (stud_detail()
), and after entering all the information of the student, s
is returned and displayed in the main function.