First, there are three ways to pass a struct as a function parameter:

The first is passing a struct variable, which is value passing; the second is passing a struct pointer, which is address passing; the third is passing struct members, which of course also includes value passing and address passing.

Passing a struct by reference is more efficient than passing it by value. Passing a struct by value requires making a copy of the entire structure.

Below is an example. The student struct contains various information about the student. We modify part of it in the change function, and then output the result in the main function.

1. Passing struct variables below

#include<stdio.h>
#include<string.h>
#define format "%d\n%s\n%f\n%f\n%f\n"
struct student
{
    int num;
    char name[20];
    float score[3];
};
void change( struct student stu );
int main()
{
    
    struct student stu;
    stu.num = 12345;
    strcpy(stu.name, "Tom");
    stu.score[0] = 67.5;
    stu.score[1] = 89;
    stu.score[2] = 78.6;
    change(stu);
    printf(format, stu.num, stu.name, stu.score[0], stu.score[1],stu.score[2]);
    printf("\n");
    return 0;
}
 
void change(struct student stu)
{
    stu.score[0] = 100;
    strcpy(stu.name, "jerry");
}

It can be seen that the final output value has not changed...

2. Address passing

#include<stdio.h>
#define format "%d\n%s\n%f\n%f\n%f\n"
struct student
{
    int num;
    char name[20];
    float score[3];
};
void change( struct student* stu );
int main()
{
    
    struct student stu;
    stu.num = 12345;
    strcpy(stu.name, "Tom");
    stu.score[0] = 67.5;
    stu.score[1] = 89;
    stu.score[2] = 78.6;
    change(&stu);
    printf(format, stu.num, stu.name, stu.score[0], stu.score[1],stu.score[2]);
    printf("\n");
    return 0;
}
 
void change(struct student* p)
{
    p->score[0] = 100;
    strcpy(p->name, "jerry");
}

It can be seen that the data in the struct has been modified through address passing.

Use &stu as the actual argument; &stu is the address of the struct variable stu. When calling the function, this address is passed to the formal parameter p (p is a pointer variable). In this way, p points to stu.

In the change function, the values of the struct members are changed, and the main function outputs the changed values.

3. Address passing and value passing of struct members

This is similar to passing a single variable, so there is no need to elaborate further; of course, only address passing can modify the value.

Passing a complete struct variable as a parameter requires passing all member values one by one, which consumes time and space and has high overhead. If the struct type has many members, or some members are arrays, the program execution efficiency will be greatly reduced. In this case, it is better to use a pointer as the function parameter, which can improve runtime efficiency.

Original address: https://blog.csdn.net/lin37985/article/details/38582027