C - Function returning structure

C Programming

Share

In this tutorial we will learn to return structure from functions in C programming language.

In the previous tutorial we learned how to pass structure to a function. Feel free to check that out if you want to recap.

First lets create a student structure.

struct student {
  char firstname[64];
  char lastname[64];
  char id[64];
  int score;
};

In this tutorial we will create a function that will return variable of type student structure.

Syntax of a function declaration returning structure

Following is the syntax of a function declaration that will return structure.

returnType functionName(dataType paramName, ...);

Example:

struct student getDetail(void);

In the above example we have a function by the name getDetail. The parameter list is set to void which means this function takes no argument.

The return type of the function is of type struct student which means it will return a value of type student structure.

Write a program in C to take details of 3 students as input and print the details using functions

In the following example we are using two functions getDetail to get student details and displayDetail to display student details.

#include <stdio.h>

// creating a student structure template
struct student {
  char firstname[64];
  char lastname[64];
  char id[64];
  int score;
};
  
// function declaration
struct student getDetail(void);
void displayDetail(struct student std);

int main(void) {
  
  // creating a student structure array variable
  struct student stdArr[3];
  
  // other variables
  int i;
  
  // taking user input
  for (i = 0; i < 3; i++) {
    printf("Enter detail of student #%d\n", (i+1));
    stdArr[i] = getDetail();
  }
  
  // output
  for (i = 0; i < 3; i++) {
    printf("\nStudent #%d Detail:\n", (i+1));
    displayDetail(stdArr[i]);
  }
  
  return 0;
}

struct student getDetail(void) {
  // temp structure variable
  struct student std;
  
  printf("Enter First Name: ");
  scanf("%s", std.firstname);
  
  printf("Enter Last Name: ");
  scanf("%s", std.lastname);
  
  printf("Enter ID: ");
  scanf("%s", std.id);
  
  printf("Enter Score: ");
  scanf("%d", &std.score);
  
  return std;
}

void displayDetail(struct student std) {
  printf("Firstname: %s\n", std.firstname);
  printf("Lastname: %s\n", std.lastname);
  printf("ID: %s\n", std.id);
  printf("Score: %d\n", std.score);
}

Output:

Enter detail of student #1
Enter First Name: Bruce
Enter Last Name: Wayne
Enter ID: dc-01
Enter Score: 8
Enter detail of student #2
Enter First Name: Peter
Enter Last Name: Parker
Enter ID: mc-01
Enter Score: 9
Enter detail of student #3
Enter First Name: Tony
Enter Last Name: Stark
Enter ID: mc-02
Enter Score: 7

Student #1 Detail:
Firstname: Bruce
Lastname: Wayne
ID: dc-01
Score: 8

Student #2 Detail:
Firstname: Peter
Lastname: Parker
ID: mc-01
Score: 9

Student #3 Detail:
Firstname: Tony
Lastname: Stark
ID: mc-02
Score: 7
Share