如何将结构的地址作为参数传递给C函数?

可以通过三种方式将结构的值从一个函数传递到另一个函数。它们如下-

  • 将单个成员作为函数的参数传递。

  • 将整个结构作为参数传递给函数。

  • 将结构的地址作为函数的参数传递。

现在,让我们了解如何将结构的地址作为函数的参数传递。

  • 结构的地址作为参数传递给函数。

  • 它收集在指向函数标头中结构的指针中。

好处

将结构的地址作为参数传递给函数的优点如下:

  • 无需浪费内存,因为无需再次创建副本。

  • 无需返回值,因为该函数可以间接访问整个结构,然后对其进行处理。

例子1

以下程序显示如何将结构的地址作为参数传递给函数-

#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\n",p->day);
   printf("month=%s\n",p->month);
   printf("year=%d\n",p->year);
}
输出结果

执行以上程序后,将产生以下结果-

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

例子2

下面给出的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\n",i,p->Name);
      printf("The Age of student %d is : %d\n",i,p->Age);
      printf("The Level of student %d is : %f\n",i,p->Level);
      printf("The Grade of student %d is : %s\n",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