创建动态链表,输入对应得分情况后按照成绩排序,但输入两组以上数据时程序会崩溃,求解答
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
struct student
{
int id;
char name[20];
float score;
struct student *next;
};
void order(struct student a[10]);
int i,n,j;float m;
int main()
{
struct student *p1,*p2,*head;
struct student a[10];
printf("输入选手人数:\n");
scanf("%d",&n);getchar();
printf("输入每个选手的id号、姓名及得分情况:\n");
p1=p2=(struct student*)malloc(sizeof(struct student));
for(i=0;i<n;i++)
{
printf("Input id and name:\n");
scanf("%d %s",&p2->id,&p2->name);
printf("Input 5 scores:\n");
p2->score=0;
for(j=0;j<5;j++)
{
scanf("%f",&m);
p2->score+=m/5.0;
}
if(i==0){head=p2;head->next=NULL;}
else
{
head->next=p2;
p2=p2->next;
}
p2=(struct student*)malloc(sizeof(struct student));
}
p2->next=NULL;
for(i=0;i<n;i++)
{
a[i].id=p1->id;
strcpy(a[i].name,p1->name);
a[i].score=p1->score;
p1=p1->next;
}
order(a);
printf("排名及每人平均分:\n");
for(i=0;i<n;i++)
printf("%d %s %.2f\n",a[i].id,a[i].name,a[i].score);
}
void order(struct student a[10])
{
struct student w;w.next=NULL;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(a[i].score<a[j].score)
{
w.id=a[i].id;
strcpy(w.name,a[i].name);
w.score=a[i].score;
a[i].id=a[j].id;
strcpy(a[i].name,a[j].name);
a[i].score=a[j].score;
a[j].id=w.id;
strcpy(a[j].name,w.name);
a[j].score=w.score;
}
}
}
输入数据为3和2时的结果:
预期结果:
望解答T^T