두 개의 다른 함수 save_struct_model_1
및 save_struct_model_2
으로 구조체의 멤버 변수를 인쇄하려고합니다. 둘 다 잘 작동하고 올바른 값을 인쇄하는 것 같습니다. 이 두 가지는 정확하고 선호되는 것입니다.C에서 구조 포인터
#include <stdio.h>
#include <stdlib.h>
struct model{
char *name;
int year;
};
void save_struct_model_1(struct model *s){
printf("%s ", s->name);
printf("%d \n",s->year);
}
void save_struct_model_2(struct model s){
printf("%s ", s.name);
printf("%d \n",s.year);
}
int main()
{
typedef struct model M;
M * honda = (M *) malloc (sizeof(M));
honda->name="civic";
honda->year=2000;
save_struct_model_1(honda);
save_struct_model_2(*honda);
return 0;
}
두 번째 사본 임시 값과 원래의 구조체를 변경할 수 없습니다. –
감사합니다. @BlagovestBuyukliev, – marc
'model_1'이 거의 항상 선호됩니다. 만약 print 만하고 싶다면'void save_struct_model_1 (const struct model * s);을 사용하십시오.'struct model {int x [1000000000]; } 그러면 스택에 4GB +를 푸시합니다. 그것은 스택을 날려 버릴 것입니다, 각 통화마다 성능 저하는 말할 것도 없습니다. 그래서 struct 포인터를 전달하는 것입니다. C를 35 년 이상 해본 적이 있는데, 모델 2를 사용할 기회가 없었습니다. –