如何使用结构体元素将各个成员作为参数传递给函数?

cserver side programmingprogramming更新于 2025/5/13 23:52:17

有三种方法可以将结构体的值从一个函数传递到另一个函数。它们如下所示 −

  • 将单个成员作为参数传递给函数。
  • 将整个结构体作为参数传递给函数。
  • 将结构的地址作为参数传递给函数。

现在让我们看看如何将结构体元素的单个成员作为参数传递给函数。

  • 每个成员在函数调用中都作为参数传递。

  • 它们在函数头中的普通变量中独立收集。

示例

下面是一个 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);// 将单个内存作为参数传递给函数
   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; // 结构体的全局声明
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

相关文章