![](/img/trans.png)
[英]C pointer to structure with elements that are pointers - how to allocate memory and use as function output
[英]How to Use Pointers to Structure to output?
一個班級有3個學生,現在我調用StuInfo(struct Student *p)
來獲取這3個學生的信息,包括ID,姓名及其分數。 我調用Rank(struct Student *p)
對他們的分數進行排名,並輸出最佳信息。 但是,每次q->scores
的輸出都是0.00000
,我不知道為什么。
這是代碼:
#include<stdio.h>
struct Student
{
int number;
char name[20];
double scores;
};
void StuInfo(struct Student *p);
void Rank(struct Student *p);
int main()
{
struct Student stus[3];
struct Student *p;
p=stus;
StuInfo(p);
Rank(p);
return 0;
}
void StuInfo(struct Student *p)
{
printf("please enter the student'ID,name,scores:");
for(int i=0;i<3;i++)
{
scanf("%d%s%f",&(p+i)->number,&(p+i)->name,&(p+i)->scores);
}
}
void Rank(struct Student *p)
{
struct Student *q;
q=p;
for(int i=0;i<2;i++)
{
if(q->scores<(p+i+1)->scores)
{
q=p+i+1;
}
}
printf("the best student's ID%d,name%s,score%f",q->number,q->name,q->scores);
}
您在scanf格式中有一個小錯誤,使用%lf來代替double而不是%f,並且使用指針時char數組名稱不需要地址運算符&(p+i)->name
。 如果要使用&地址運算符作為名稱,則必須指向數組的第一個元素,例如&(p+i)->name[0]
我的意思是您的代碼應該可以工作
void StuInfo(struct Student *p)
{
printf("please enter the student'ID,name,scores:");
for(int i=0;i<3;i++)
{
scanf("%d%s%lf",&(p+i)->number,(p+i)->name,&(p+i)->scores);// here
}
}
我可以建議以下幾點技巧來使代碼在處理指針算術時更具可讀性和簡單性。
您將需要修復scanf
格式說明符,這就是為什么您要繼續讀取0.0000
作為分數的原因。 要解決此問題,請將最后一個%f
更改為%lf
。
您可以簡化此處的所有指針和偏移量:
scanf("%d%s%f",&(p+i)->number,&(p+i)->name,&(p+i)->scores);
只是以下內容:
scanf("%d%s%lf", &p->number, &p->name, &p->scores);
p++;
由於p
指向struct Student
的大小,因此在執行p++
時它將自動增加到下一個元素。 這更容易閱讀,並減少了出現指針算術錯誤的機會!!
您還可以清理最后一個循環,以避免算術錯誤並簡化操作,如下所示:
void Rank(struct Student *p) { struct Student *q; q = p; for (int i = 0; i<2; i++) { p++; if (q->scores < p->scores) { q = p; } } printf("the best student's ID: %d,name: %s,score: %f\\n", q->number, q->name, q->scores) }
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.