我是C和整体编程的初学者,所以对可能出现的琐碎错误感到抱歉。让我简要解释一下我的情况。
我有结构学生:
typedef struct {
int id;
char name[20]
int grade;
} students;
我有一个变量students student[20]
,其中包含每个学生的姓名、ID 和成绩
并且还有一个类型学生的指针函数(我希望我正确调用它,如果错误请纠正我),它必须将指针返回给成绩最高的学生:
students* topStudent(students student[20]) {
...
//let's say I have found the student with the top grades and his index is 4.
return &student[4];
}
现在,假设我想管理这个学生[4],但是,我该怎么做?例如,我想将student[4]
的字段(id等)复制到另一个变量students topstudent
中,以便我直接进一步使用它。
我试过这个:
students *topstudent;
topstudent = topStudent(student);
但是每当我尝试使用topstudent
,例如这样:
printf("%i %s %i", topstudent.id, topstudent.name, topstudent.grade);
或者当我尝试将&
放在topstudent.id
、topstudent.name
和topstudent.grade
之前时,它为每个字段(request for member 'name' in something not a structure or union
)给出了 3 个错误。(我想topstudent
的声明和使用有问题,或者我没有为指针应用正确的方法,或者我缺少其他东西)。
那么,你能告诉我正确的方法吗?如果需要,请随时了解详细信息。谢谢,非常感谢您的帮助!
>topstudent
是一个指针,因此您必须取消引用它才能访问该结构。
可以使用一元运算符*
取消引用指针。
printf("%i %s %i", (*topstudent).id, (*topstudent).name, (*topstudent).grade);
或者,您可以使用->
运算符。A->B
意味着(*A).B
。
printf("%i %s %i", topstudent->id, topstudent->name, topstudent->grade);