C語言 結構體作為函數的參數


1)使用結構體變量作為函數的參數

  使用結構體變量作為函數的實參時,采用的是值傳遞,會將結構體變量所占內存單元的內容全部順序傳遞給形參,形參必須是同類型的結構體變量

demo:

 1 # include <stdio.h>
 2 # include <stdlib.h>
 3 
 4 //創建一個Student結構 
 5 struct Student
 6 {
 7     char name[30];
 8     float fScore[3];
 9 }student={"dire",98.5,89.0,93.5}; //初始化結構體變量 
10 
11 void Display(struct Student su) //形參為同類型的結構體(Student結構) 
12 {
13     printf("-----Information------\n");
14     printf("Name:%s",su.name);
15     printf("Chinese:%.2f\n",su.fScore[0]);
16     printf("Math:%.2f\n",su.fScore[1]);
17     printf("English:%.2f",su.fScore[2]);
18     printf("平均分數為:%.2f\n",(su.fScore[0]+su.fScore[1],su.fScore[2])/3);
19 }
20 
21 int main ()
22 {
23     
24     Display(student);
25     
26     return 0;
27  } 

Printf:


2)使用指向結構體變量的指針作為函數參數

Demo:

 1 # include <stdio.h>
 2 # include <stdlib.h>
 3 
 4 struct Student {
 5     char name[20];
 6     float fScore[3];
 7 }student = {"dire",98.5,89.0,93.5}; //初始化結構體變量 
 8 
 9 
10 void Display(struct Student *pStruct)
11 {
12     printf("------Information-------\n");
13     printf("Name:%s\n",pStruct->name);
14     printf("Chinese:%.2f\n",(*pStruct).fScore[0]);
15     printf("Math:%.2f\n",(*pStruct).fScore[1]);
16     printf("English:%.2f\n",pStruct->fScore[2]);
17 }
18 
19 
20 int main ()
21 {
22     Display(&student);        //將結構體變量的首地址作為實參傳入pStruct指針變量中 
23     
24     return 0;
25 } 

3)使用結構體變量的成員作為函數參數

  這種方式為函數傳遞參數與普通的變量作為實參是一樣的,是值傳遞

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM