问题遇到的现象和发生背景
用vs2019写利用堆排序实现学生成绩管理
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int n;
typedef struct student {
char num[20];
char name[25];
int score;
}*Stu, StuNode;
void Build(Stu stu)
{
FILE* fp;
char name[20];
int score, i;
char num[20];
fp = fopen("E:\Student.txt", "w");
printf("请输入学生人数:");
scanf("%d", &n);
printf("请输入学生信息(学号,姓名,成绩):\n");
for (i = 1; i <= n; i++)
{
scanf("%s %s %d", num, name, &score);
fprintf(fp, "%s %s %d\n", num, name, score);
}
printf("登录成功.\n");
fclose(fp);
}
void ReadFile(Stu& stu)
{//读文件,存到Stu结构体中
FILE* fp;
int i;
stu = (Stu)malloc(sizeof(StuNode) * (n + 1));
fp = fopen("E:\Student.txt", "r");
for (i = 1; i <= n; i++)
fscanf(fp, "%s %s %d", stu[i].num, stu[i].name, &stu[i].score);
fclose(fp);
}
void Display(Stu stu)
{//显示数据
int i;
int temp = 1, index = 0;
for (i = 1; i <= n; i++)
{
printf("%2d %15s %15s %5d\n", temp, stu[i].num, stu[i].name, stu[i].score);
if (i < n && stu[i].score == stu[i + 1].score)
index++;
else
{
temp += index + 1;
index = 0;
}
}
free(stu);
}
void Swap(StuNode& a, StuNode& b)
{
StuNode temp;
temp = a;
a = b;
b = temp;
}
void HeapAdjust(Stu stu, int s, int m)
{//调整堆
int j;
StuNode rc;
rc = stu[s];
for (j = 2 * s; j <= m; j *= 2)
{
if (j<m && stu[j].score>stu[j + 1].score)
j++;
if (!(rc.score > stu[j].score))
break;
stu[s] = stu[j];
s = j;
}
stu[s] = rc;
}
void HeapSort(Stu stu)
{//堆排序
int i;
ReadFile(stu);
for (i = n / 2; i > 0; i--)
HeapAdjust(stu, i, n);
for (i = n; i > 1; i--)
{
Swap(stu[1], stu[i]);
HeapAdjust(stu, 1, i - 1);
}
Display(stu);
}
int main()
{
Stu stu;
int key;
while (1)
{
printf(" ----------------------\n");
printf(" 1.录入学生基本信息。\n");
printf(" 2.堆排序。\n");
printf(" 3.输出学生信息。\n");
printf(" 4.退出。\n");
printf(" ----------------------\n");
scanf("%d", &key);
stu = NULL;
switch (key)
{
case 1:
Build(stu);
break;
case 2:
HeapSort(stu);
break;
case 3:
ReadFile(stu);
Display(stu);
break;
default:
return 0;
}
}
}
运行结果及报错内容
我想要达到的结果
正常运行