如何在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP