將一個結構體變量的值傳遞給另一個函數,有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]); }