如何使用结构体元素将各个成员作为参数传递给函数?
结构体值的传递方式有三种,如下所示:
- 将各个成员作为参数传递给函数。
- 将整个结构体作为参数传递给函数。
- 将结构体的地址作为参数传递给函数。
现在让我们看看如何将结构体元素的各个成员作为参数传递给函数。
每个成员在函数调用中作为参数传递。
它们在函数头部的普通变量中独立收集。
示例
下面是一个 C 程序,演示了将结构体的各个参数传递给函数:
#include<stdio.h>
struct date{
int day;
int mon;
int yr;
};
main ( ){
struct date d= {02,01,2010}; // struct date d;
display(d.day, d.mon, d.yr);// passing individual mem as argument to function
getch ( );
}
display(int a, int b, int c){
printf("day = %d
", a);
printf("month = %d
",b);
printf("year = %d
",c);
}输出
执行上述程序时,将产生以下结果:
day = 2 month = 1 year = 2010
示例 2
考虑另一个示例,其中解释了下面一个 C 程序,该程序演示了将结构体的各个参数传递给函数:
#include <stdio.h>
#include <string.h>
struct student{
int id;
char name[20];
float percentage;
char temp;
};
struct student record; // Global declaration of structure
int main(){
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo(record.id,record.name,record.percentage);
return 0;
}
void structure_demo(int id,char name[],float percentage){
printf(" Id is: %d
", id);
printf(" Name is: %s
", name);
printf(" Percentage is: %.2f
",percentage);
}输出
执行上述程序时,将产生以下结果:
Id is: 1 Name is: Raju Percentage is: 86.5
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP