【发布时间】:2020-06-28 19:09:33
【问题描述】:
#include <stdio.h>
int j=0;
struct student
{
int CNE;
char Nom[20];
char Prenom[20];
char Ville[20];
float Note[3];
float Moyenne;
};
void read_struct(struct student stu)
{
stu.Moyenne=0;
printf("Nom de l'etudiant:\t ");
scanf(" %s",stu.Nom);
printf("Prenom de l'etudiant:\t ");
scanf(" %s",stu.Prenom);
printf("CNE de l'etudiant:\t ");
scanf("%d",&stu.CNE);
}
int main()
{
struct student stu[10];
read_struct(stu[0]);
read_struct(stu[1]);
printf("%s \n %s \n",stu[0].Nom,stu[1].Nom);
printf("%d \n %d",stu[0].CNE,stu[1].CNE);
}
编译后我得到了一些奇怪的输出,用户的输入在回调后没有保存在结构中。(对不起我的英语)
【问题讨论】:
-
read_struct(struct student stu)接收结构的副本,因此在该函数中所做的任何更改都不会在main()中看到。 C 是按值传递。您需要传递结构read_struct(struct student *stu)的地址,以便在函数内更新该地址处的结构。您在 main 中的调用将是,例如read_struct(&stu[0]); -
你的
struct student是按值传递给read_struct()的,因此该函数正在修改结构的本地副本。搜索“按值传递”和“按引用传递” -
您通过值传递结构,即您的函数
read_struct使用该结构的本地副本,该副本不会传递给调用main函数。将函数参数更改为指向结构的指针,并在main中传递结构的地址 -
成功了,谢谢。但是我不得不将 stu.Nom 更改为 stu->Nom,我从警告中得到它并且它有效,你能向我解释为什么我也应该改变它吗?谢谢你的回答。
标签: c struct pass-by-value