구조 값이 한 기능에서 다른 기능으로 전송되는 세 가지 방법이 있습니다. 다음과 같습니다 -
-
개별 멤버를 함수에 대한 인수로 전달합니다.
-
전체 구조를 함수에 대한 인수로 전달합니다.
-
구조체의 주소를 함수에 대한 인수로 전달합니다.
이제 구조체의 주소를 함수의 인수로 전달하는 방법을 알아보겠습니다.
-
구조체의 주소는 함수에 인수로 전달됩니다.
-
함수 헤더의 구조체에 대한 포인터로 수집됩니다.
장점
구조체의 주소를 함수에 대한 인수로 전달할 때의 이점은 다음과 같습니다. -
-
복사본을 다시 만들 필요가 없으므로 메모리 낭비가 없습니다.
-
함수가 전체 구조에 간접적으로 액세스한 다음 작업할 수 있으므로 값을 반환할 필요가 없습니다.
예시
다음 프로그램은 구조체의 주소를 함수에 인수로 전달하는 방법을 보여줍니다 -
#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\n",p->day);
printf("month=%s\n",p->month);
printf("year=%d\n",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\n",i,p->Name);
printf("The Age of student %d is : %d\n",i,p->Age);
printf("The Level of student %d is : %f\n",i,p->Level);
printf("The Grade of student %d is : %s\n",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