Reputation:
I am a beginner in C and programming overall, so sorry for the possible trivial mistakes. 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
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?
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.
I tried this:
students *topstudent;
topstudent = topStudent(student);
but whenever I try to work with topstudent
, for example like this:
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
). (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).
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!
Upvotes: 1
Views: 64
Reputation: 75062
topstudent
is a pointer, so you have to dereference that to access the structure.
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
.
printf("%i %s %i", topstudent->id, topstudent->name, topstudent->grade);
Upvotes: 3