将一个结构体变量中的数据传递给另一个函数,有下列3种方法:
- 用结构体变量名作参数。一般较少用这种方法。
- 用指向结构体变量的指针作实参,将结构体变量的地址传给形参。
- 用结构体变量的引用变量作函数参数。
下面通过一个简单的例子来说明,并对它们进行比较。
有一个结构体变量stu,内含学生学号、姓名和3门课的成绩。要求在main函数中为各成员赋值,在另一函数print中将它们的值输出。
1.结构体变量作函数参数
/*************************************************************************
> File Name: test.c
> Author: zhengdongqi
> Mail:
> Created Time: 一 4/15 19:36:06 2019
************************************************************************/
#include <stdio.h>
#include <string.h>
struct Student {
int num;
char *name;
float score[3];
};
void print(struct Student st) {
printf("%d, %s, %0.1f %0.1f %0.1f\n", st.num, st.name, st.score[0], st.score[1], st.score[2]);
}
int main() {
struct Student stu; //定义结构体变量
stu.num = 12345; //以下5行对结构体变量各成员赋值
stu.name = "zhengdongqi";
stu.score[0] = 67.5;
stu.score[1] = 89;
stu.score[2] = 78.5;
print(stu); //调用print函数,输出stu各成员的值
return 0;
}
2.用指向结构体变量的指针作实参在上面程序的基础上稍作修改即可
/*************************************************************************
> File Name: test.c
> Author: zhengdongqi
> Mail:
> Created Time: 一 4/15 19:36:06 2019
************************************************************************/
#include <stdio.h>
#include <string.h>
struct Student {
int num;
char *name;
float score[3];
};
//定义函数,形参p是基类型为Student的指针变量
void print(struct Student *st) {
printf("%d, %s, %0.1f %0.1f %0.1f\n", st->num, st->name, st->score[0], st->score[1], st->score[2]);
}
int main() {
struct Student stu; //定义结构体变量
stu.num = 12345; //以下5行对结构体变量各成员赋值
stu.name = "zhengdongqi";
stu.score[0] = 67.5;
stu.score[1] = 89;
stu.score[2] = 78.5;
struct Student *ptr = &stu; //定义基类型为Student的指针变量ptr,并指向stu
print(ptr); //实参为指向Student类数据的指针变量
return 0;
}
调用print函数时,实参指针变量pt将stu的起始地址传送给形参p(p也是基类型为student的指针变量)。这样形参p也就指向stu
在print函数中输出p所指向的结构体变量的各个成员值,它们也就是stu的成员值。在main函数中也可以不定义指针变量pt,而在调用print函数时以&stu作为实参,把stu的起始地址传给实参p。
3.用结构体变量的引用作函数参数
C++中使用
/*************************************************************************
> File Name: test.cpp
> Author: zhengdongqi
> Mail:
> Created Time: 一 4/15 20:07:51 2019
************************************************************************/
#include <iostream>
#include <string>
using namespace std;
struct Student {
int num;
string name;
float score[3];
}stu={12345, "zhengdongqi", 67.5, 89, 78.5};
//函数定义,形参为结构体Student变量的引用
void print(Student &stud) {
cout<<stud.num<<" "<<stud.name<<" "<<stud.score[0]
<<" " <<stud.score[1]<<" "<<stud.score[2]<<endl;
}
int main() {
void print(Student &);
//函数声明,形参为Student类型变量的引用
print(stu);
//实参为结构体Student变量
return 0;
}
4、总结
程序(1)用结构体变量作实参和形参,程序直观易懂,效率是不高的。
程序(2)采用指针变量作为实参和形参,空间和时间的开销都很小,效率较高。但程序(2)不如程序(1)那样直接。
程序(3)的实参是结构体Student类型变量,而形参用Student类型的引用,虚实结合时传递的是stu的地址,因而效率较高。它兼有(1)和(2)的优点。