簡體   English   中英

C語言。 如何管理函數返回的結構體?

[英]C language. How to manage the struct returned by a function?

我是 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.idtopstudent.nametopstudent.grade ,它會為每個字段提供 3 個錯誤( request for member 'name' in something not a structure or union )。 (我想topstudent的聲明和使用有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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM