如何在C語言中將整個結構體作為引數傳遞給函式?


將結構體中的值從一個函式傳遞到另一個函式,有三種方法。它們如下所示:

  • 將各個成員作為引數傳遞給函式。

  • 將整個結構體作為引數傳遞給函式。

  • 將結構體的地址作為引數傳遞給函式。

現在讓我們看看如何將整個結構體作為引數傳遞給函式。

  • 結構體變數的名稱作為引數在函式呼叫中給出。

  • 它在函式頭中被收集到另一個結構體變數中。

  • 缺點是會再次建立整個結構體的副本,從而浪費記憶體。

示例

以下程式展示瞭如何將整個結構體作為引數傳遞給函式。

 線上演示

#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
",d.day);    printf("month=%s
",d.month);    printf("year=%d
",d.year); }

輸出

當執行上述程式時,它會產生以下結果:

enter the day, month and year:18 JAN 2021
day=18
month=JAN
year=2021

示例 2

考慮另一個示例,其中解釋了 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

示例 3

另一個 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
",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

更新於: 2021年3月24日

3K+ 閱讀量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告