如何在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);
   return 0;
}
void display(struct date *p){
   printf("day=%d
",p->day);    printf("month=%s
",p->month);    printf("year=%d
",p->year); }

輸出

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

enter the day, month and year:20 MAR 2021
day=20
month=MAR
year=2021

示例

下面是一個C程式,透過將整個函式作為引數來演示結構體和函式。由於這種函式呼叫方法,不會浪費記憶體,因為我們不需要再次複製和返回值。

 線上演示

#include<stdio.h>
//Declaring structure//
struct student{
   char Name[100];
   int Age;
   float Level;
   char Grade[50];
   char temp;
}s[5];
//Declaring and returning Function//
void show(struct student *p){
   //Declaring variable for For loop within the function//
   int i;
   //For loop for printing O/p//
   for(i=1;i<3;i++){
      printf("The Name of student %d is : %s
",i,p->Name);       printf("The Age of student %d is : %d
",i,p->Age);       printf("The Level of student %d is : %f
",i,p->Level);       printf("The Grade of student %d is : %s
",i,p->Grade);       p++;    } } void main(){    //Declaring variable for for loop//    int i;    //Declaring structure with pointer//    struct student *p;    //Reading User I/p//    for(i=0;i<2;i++){       printf("Enter the Name of student %d : ",i+1);       gets(s[i].Name);       printf("Enter the Age of student %d : ",i+1);       scanf("%d",&s[i].Age);       printf("Enter the Level of student %d :",i+1);       scanf("%f",&s[i].Level);       scanf("%c",&s[i].temp);//Clearing Buffer//       printf("Enter the Grade of student %d :",i+1);       gets(s[i].Grade);    }    //Assigning pointer to structure//    p=&s;    //Calling function//    show(&s); }

輸出

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

Enter the Name of student 1 : Lucky
Enter the Age of student 1 : 27
Enter the Level of student 1 :2
Enter the Grade of student 1 :A
Enter the Name of student 2 : Pinky
Enter the Age of student 2 : 29
Enter the Level of student 2 :1
Enter the Grade of student 2 :B
The Name of student 1 is : Lucky
The Age of student 1 is : 27
The Level of student 1 is : 2.000000
The Grade of student 1 is : A
The Name of student 2 is : Pinky
The Age of student 2 is : 29
The Level of student 2 is : 1.000000
The Grade of student 2 is : B

更新於:2021年3月24日

7K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告