How to Pass a structure as an argument to the functions?

When passing structures to or from functions in C, it is important to keep in mind that the entire structure will be copied. This can be expensive in terms of both time and memory, especially for large structures. The passing of structure to the function can be done in two ways:

  • By passing all the elements to the function individually.
  • By passing the entire structure to the function.

Example 1: Using Call By Value Method

C




// C program to pass structure as an argument to the
// functions using Call By Value Method
#include <stdio.h>
 
struct car {
    char name[30];
    int price;
};
 
void print_car_info(struct car c)
{
    printf("Name : %s", c.name);
    printf("\nPrice : %d\n", c.price);
}
 
int main()
{
    struct car c = { "Tata", 1021 };
    print_car_info(c);
    return 0;
}


Output

Name : Tata
Price : 1021

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2: Using Call By Reference Method

C




// C program to pass structure as an argument to the
// functions using Call By Reference Method
 
#include <stdio.h>
 
struct student {
    char name[50];
    int roll;
    float marks;
};
 
void display(struct student* student_obj)
{
    printf("Name: %s\n", student_obj->name);
    printf("Roll: %d\n", student_obj->roll);
    printf("Marks: %f\n", student_obj->marks);
}
int main()
{
    struct student st1 = { "Aman", 19, 8.5 };
 
    display(&st1);
 
    return 0;
}


Output

Name: Aman
Roll: 19
Marks: 8.500000

Time Complexity: O(1)
Auxiliary Space: O(1)

How to Pass or Return a Structure To or From a Function in C?

A structure is a user-defined data type in C. A structure collects several variables in one place. In a structure, each variable is called a member. The types of data contained in a structure can differ from those in an array (e.g., integer, float, character).

Syntax:

struct w3wiki
{
    char name[20];
    int roll_no;
    char branch[20];
}

 

Similar Reads

How to Pass a structure as an argument to the functions?

When passing structures to or from functions in C, it is important to keep in mind that the entire structure will be copied. This can be expensive in terms of both time and memory, especially for large structures. The passing of structure to the function can be done in two ways:...

How to Return a Structure From functions?

...