[英]C language. How to manage the struct returned by a function?
I am a beginner in C and programming overall, so sorry for the possible trivial mistakes.我是 C 和编程的初学者,对于可能的微不足道的错误,我深表歉意。 Let me briefly explain my case.让我简要说明一下我的情况。
I have the struct students:我有结构学生:
typedef struct {
int id;
char name[20]
int grade;
} students;
and I have the variable students student[20]
that contains names, ids and grades of each student我有变量students student[20]
,其中包含每个学生的姓名、ID 和成绩
and also have a pointer function of type students (I hope I am calling it properly, correct me if wrong) which has to return the pointer to the student with the highest grades:并且还有一个学生类型的指针函数(我希望我正确调用它,如果错误请纠正我)它必须将指针返回给分数最高的学生:
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];
}
Now, let's say I want to manage this student[4], but, How do I do that?现在,假设我想管理这个学生 [4],但是,我该怎么做? For instance, I want to have student[4]
's fields (id, etc.) copied in another variable students topstudent
so that I directly worked with it further.例如,我希望将student[4]
的字段(id 等)复制到另一个变量students topstudent
以便我直接进一步使用它。
I tried this:我试过这个:
students *topstudent;
topstudent = topStudent(student);
but whenever I try to work with topstudent
, for example like this:但是每当我尝试与topstudent
,例如这样:
printf("%i %s %i", topstudent.id, topstudent.name, topstudent.grade);
or when I tried to put &
before the topstudent.id
, topstudent.name
and topstudent.grade
, it gives 3 errors for each of the fields ( request for member 'name' in something not a structure or union
).或者当我尝试将&
放在topstudent.id
、 topstudent.name
和topstudent.grade
,它会为每个字段提供 3 个错误( request for member 'name' in something not a structure or union
)。 (I guess there's something wrong with the declaration and using of topstudent
, or I am not applying correct methods for pointers, or something else I am missing). (我想topstudent
的声明和使用有topstudent
,或者我没有对指针应用正确的方法,或者我缺少的其他东西)。
So, could you please tell me the correct way of doing that?所以,你能告诉我正确的做法吗? Feel free to get to know the details, if needed.如果需要,请随时了解详细信息。 Thank you, I do appreciate your help!谢谢你,我非常感谢你的帮助!
topstudent
is a pointer, so you have to dereference that to access the structure. topstudent
是一个指针,因此您必须取消引用它才能访问该结构。
You can use unary *
operator to dereference a pointer.您可以使用一元*
运算符来取消引用指针。
printf("%i %s %i", (*topstudent).id, (*topstudent).name, (*topstudent).grade);
Alternatively, you can use ->
operator.或者,您可以使用->
运算符。 A->B
means (*A).B
. A->B
表示(*A).B
。
printf("%i %s %i", topstudent->id, topstudent->name, topstudent->grade);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.