如何将整个结构作为参数传递给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 d){
printf("day=%d\n",d.day);
printf("month=%s\n",d.month);
printf("year=%d\n",d.year);
}
执行以上程序后,将产生以下结果-
enter the day, month and year:18 JAN 2021day=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 = 20Enter 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\n",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 = 25Enter 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函数? 的全部内容, 来源链接: utcz.com/z/329659.html