在本教程中,您將學(xué)習(xí)將結(jié)構(gòu)變量作為參數(shù)傳遞給函數(shù)。您將學(xué)習(xí)借助示例從函數(shù)返回struct的方法。
與內(nèi)置類(lèi)型的變量類(lèi)似,您也可以將結(jié)構(gòu)變量傳遞給函數(shù)。
我們建議您在學(xué)習(xí)如何將結(jié)構(gòu)傳遞給函數(shù)之前先學(xué)習(xí)這些教程。
這是將結(jié)構(gòu)傳遞給函數(shù)的方法
#include <stdio.h> struct student { char name[50]; int age; }; //函數(shù)原型 void display(struct student s); int main() { struct student s1; printf("輸入姓名: "); //讀取用戶輸入的字符串,直到輸入\ n // \ n被丟棄 scanf("%[^\n]%*c", s1.name); printf("輸入年齡: "); scanf("%d", &s1.age); display(s1); //將struct作為參數(shù)傳遞 return 0; } void display(struct student s) { printf("\n顯示信息\n"); printf("姓名: %s", s.name); printf("\n年齡: %d", s.age); }
輸出結(jié)果
輸入姓名: Bond 輸入年齡: 13 顯示信息 姓名: Bond 年齡: 13
在這里,創(chuàng)建了struct student類(lèi)型的struct變量s1。 使用display(s1)將變量傳遞給display()函數(shù)聲明。
這是從函數(shù)返回結(jié)構(gòu)的方法:
#include <stdio.h> struct student { char name[50]; int age; }; //函數(shù)原型 struct student getInformation(); int main() { struct student s; s = getInformation(); printf("\n顯示信息\n"); printf("Name: %s", s.name); printf("\nRoll: %d", s.age); return 0; } struct student getInformation() { struct student s1; printf("輸入姓名: "); scanf ("%[^\n]%*c", s1.name); printf("輸入年齡: "); scanf("%d", &s1.age); return s1; }
在這里,使用s = getInformation()來(lái)調(diào)用getInformation()函數(shù)聲明。 該函數(shù)返回struct學(xué)生類(lèi)型的結(jié)構(gòu)。 在main()函數(shù)中顯示返回的結(jié)構(gòu)。
注意,getInformation()的返回類(lèi)型也是struct student。
您還可以按引用傳遞結(jié)構(gòu)(就像您按引用傳遞內(nèi)置類(lèi)型的變量一樣)。我們建議您在繼續(xù)之前閱讀參考指南。
在按引用傳遞期間,結(jié)構(gòu)變量的內(nèi)存地址將傳遞給函數(shù)。
#include <stdio.h> typedef struct Complex { float real; float imag; } complex; void addNumbers(complex c1, complex c2, complex *result); int main() { complex c1, c2, result; printf("輸入第一個(gè)數(shù):\n"); printf("輸入實(shí)部: "); scanf("%f", &c1.real); printf("輸入虛部: "); scanf("%f", &c1.imag); printf("輸入第二個(gè)數(shù): \n"); printf("輸入實(shí)部: "); scanf("%f", &c2.real); printf("輸入虛部: "); scanf("%f", &c2.imag); addNumbers(c1, c2, &result); printf("\nresult.real = %.1f\n", result.real); printf("result.imag = %.1f", result.imag); return 0; } void addNumbers(complex c1, complex c2, complex *result) { result->real = c1.real + c2.real; result->imag = c1.imag + c2.imag; }
輸出結(jié)果
輸入第一個(gè)數(shù): 輸入實(shí)部: 5.8 輸入虛部: -3.4 輸入第二個(gè)數(shù): 輸入實(shí)部: 9.9 輸入虛部: -4.5 result.real = 15.7 result.imag = -7.9
在上面的程序中,三個(gè)結(jié)構(gòu)變量c1,c2和結(jié)果的地址傳遞給addNumbers()函數(shù)。 在這里,結(jié)果通過(guò)引用傳遞。
當(dāng)addNumbers()內(nèi)部的結(jié)果變量被更改時(shí),main()函數(shù)內(nèi)部的結(jié)果變量也被相應(yīng)地更改。