【问题标题】:Error initializing structures with helper function使用辅助函数初始化结构时出错
【发布时间】: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(&amp;stu[0]);
  • 你的struct student 是按值传递给read_struct() 的,因此该函数正在修改结构的本地副本。搜索“按值传递”和“按引用传递”
  • 您通过值传递结构,即您的函数 read_struct 使用该结构的本地副本,该副本不会传递给调用 main 函数。将函数参数更改为指向结构的指针,并在main 中传递结构的地址
  • 成功了,谢谢。但是我不得不将 stu.Nom 更改为 stu->Nom,我从警告中得到它并且它有效,你能向我解释为什么我也应该改变它吗?谢谢你的回答。

标签: c struct pass-by-value


【解决方案1】:

看看这个函数是怎么定义的:

void read_struct(struct student stu) {
    ...
}

当您调用此函数时,它会传入struct student副本,因此该函数会完成其工作以填充副本而不是原始文件。

您可能希望此函数接收指向 struct student 的指针:

void read_struct(struct student* stu) {
    /* You'll need to change things here */
}

read_student(&stu[0]);
read_student(&stu[1]);

希望这会有所帮助!

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2015-02-19
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多