结构指针变量作函数参数
将一个结构体变量的值传递给另一个函数,有3种方法:
(1)用结构体变量的成员做参数。
(2)用结构体变量做实参。
(3)用指向结构体变量的指针做实参,将结构体变量的地址传给形参。
例:有一个结构体变量stu,内含学生学号、姓名和3门课程的成绩。通过调用函数print将他们输出。
要求:用结构体变量做函数实参:
#include "StdAfx.h" #include<stdio.h> #include<string.h> struct student { int num; char name[20]; float score[3]; }; void print(struct student); void main() { struct student stu; stu.num=8; strcpy(stu.name,"lv"); //若直接赋值,则name必须为指针 stu.score[0]=98.5; stu.score[1]=99.0; stu.score[2]=99.5; print(stu); } void print(struct student stu) { printf("\t num:%d\n",stu.num); printf("\tname:%s\n",stu.name); printf("\tscore_1:%5.2f",stu.score[0]); printf("\tscore_2:%5.2f",stu.score[1]); printf("\tscore_3:%5.2f",stu.score[2]); }
用指向结构体变量的指针做实参:
#include "StdAfx.h" #include<stdio.h> #include<string.h> struct student { int num; char name[20]; float score[3]; }; void print(struct student*); void main() { struct student stu; stu.num=8; strcpy(stu.name,"lv"); //若直接赋值,则name必须为指针 stu.score[0]=98.5; stu.score[1]=99.0; stu.score[2]=99.5; print(&stu); } void print(struct student *stu) { printf("\t num:%d\n",stu->num); printf("\tname:%s\n",stu->name); printf("\tscore_1:%5.2f",stu->score[0]); printf("\tscore_2:%5.2f",stu->score[1]); printf("\tscore_3:%5.2f",stu->score[2]); }