Structs and Functions in C

In this lesson, you will learn how to pass structs to a function in C as a parameter, with an example to understand the topic better.

Passing struct to a function as an argument

In the lesson User Defined Functions in C, we learned how to pass an argument for any data type to a function. Structs are user-defined data types, and they are no exception. A struct can be passed to a function as an argument.

Example

Below, we define a student struct, which we will use to create an instant from the main function, then pass that instance to a function that prints out the struct element values.

#include <stdio.h>
// Student Struct

struct student {
  char name[20];
  int age;
  char grade[1];

};
// function prototype
void PrintStruct(struct student student);

// function implementation 
void PrintStruct(struct student student) {
   printf("\nYou entered:\n");
   printf("Name: %s", student.name);
   printf("\nAge: %i", student.age);
   printf("\nGrade: %s", student.grade);
}
// main function
int main() {
  struct student s;

  printf("Enter student name: ");
  scanf("%[^\n]%*c", s.name);

  printf("Enter student age: ");
  scanf("%i", & s.age);

  printf("Enter student grade: ");
  scanf("%s", & s.grade);

  PrintStruct(s); // Passint struct to function as a parameter

  return 0;
}

Output

Enter student name: Fred
Enter student age: 24
Enter student grade: B
You entered:
Name: Fred
Age: 24
Grade: B

 Summary

  •  Structs can be passed to a function as arguments.

 

 

 

Back to: Learn C Programming > Structures and Unions

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.