如何使用結構體元素將各個成員作為引數傳遞給函式?
結構體值的傳遞方式有三種,如下所示:
- 將各個成員作為引數傳遞給函式。
- 將整個結構體作為引數傳遞給函式。
- 將結構體的地址作為引數傳遞給函式。
現在讓我們看看如何將結構體元素的各個成員作為引數傳遞給函式。
每個成員在函式呼叫中作為引數傳遞。
它們在函式頭部的普通變數中獨立收集。
示例
下面是一個 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