有三種方法可以將結構的值從一個函數傳遞到另一個函數。它們如下所示:
將單一成員作為參數傳遞給函數。
將整個結構作為參數傳遞給函數。
將結構的位址作為參數傳遞給函數。
現在讓我們看看如何將整個結構作為參數傳遞給函數。
在函數呼叫中給出結構變數的名稱作為參數。
在函數頭中將其收集到另一個結構變數中。
缺點是浪費內存,會再次建立整個結構的副本。
以下程式示範如何將整個結構作為參數傳遞給函數。
示範
#include<stdio.h> struct date{ int day; char month[10]; int year; }; int main(){ struct date d; printf("enter the day,month and year:"); scanf("%d%s%d",&d.day,d.month,&d.year); display(d);//passing entire structure as an argument to function return 0; } void display(struct date d){ printf("day=%d</p><p>",d.day); printf("month=%s</p><p>",d.month); printf("year=%d</p><p>",d.year); }
當上述程式被執行時,它產生以下結果−
enter the day, month and year:18 JAN 2021 day=18 month=JAN year=2021
考慮另一個例子,在這個例子中,解釋了一個C程式如何將整個結構體作為參數傳遞給函數。
線上示範
#include<stdio.h> //Declaring structure// struct add{ int var1; int var2; }a; //Declaring and returning Function// void show(struct add a){ //Declaring sum variable// int sum; //Arithmetic Operation// sum=a.var1+a.var2; //Printing O/p// printf("Added value is %d",sum); } void main(){ //Declaring structure// struct add a; //Reading User I/p// printf("Enter variable 1 = "); scanf("%d",&a.var1); printf("Enter variable 2 = "); scanf("%d",&a.var2); //Calling function// show(a); }
當上述程式被執行時,它產生以下結果−
Enter variable 1 = 20 Enter variable 2 = 50 Added value is 70
這是另一個C程序,演示了將整個結構作為參數傳遞給函數的方法,其中解釋了聲明結構、聲明和返回函數等內容。
線上示範
#include<stdio.h> //Declaring structure// struct student{ int s1,s2,s3; }s[5]; //Declaring and returning Function// void addition(struct student s[]){ //Declaring sum variable and For loop variable// int i,sum; //Arithmetic Operation// for(i=1;i<4;i++){ sum=s[i].s1+s[i].s2+s[i].s3; printf("Student %d scored total of %d</p><p>",i,sum); } } void main(){ //Declaring variable for For loop// int i; //Reading User I/p through For loop// for(i=1;i<4;i++){ printf("Enter marks for student %d in subject 1 = ",i); scanf("%d",&s[i].s1); printf("Enter marks for student %d in subject 2 = ",i); scanf("%d",&s[i].s2); printf("Enter marks for student %d in subject 3 = ",i); scanf("%d",&s[i].s3); } //Calling function// addition(s); }
當上述程式被執行時,它產生以下結果 −
Enter marks for student 1 in subject 1 = 25 Enter marks for student 1 in subject 2 = 89 Enter marks for student 1 in subject 3 = 45 Enter marks for student 2 in subject 1 = 12 Enter marks for student 2 in subject 2 = 45 Enter marks for student 2 in subject 3 = 89 Enter marks for student 3 in subject 1 = 12 Enter marks for student 3 in subject 2 = 78 Enter marks for student 3 in subject 3 = 12 Student 1 scored total of 159 Student 2 scored total of 146 Student 3 scored total of 102
以上是如何在C語言中將整個結構作為參數傳遞給函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!