//test03
#include <stdio.h>
#include <stdlib.h>
struct student {
int sno;
char name[20];
float scores[3];
float average;
float sum;
};
struct NODE {
struct student data;
struct NODE *next;
};
int main() {
int num = 0;
printf("please input the number of students: ");
scanf("%d", &num);
fflush(stdin);
printf("please input the student's information: \n");
struct NODE *head = NULL;
for (int i = 0; i < num; ++i) {
struct NODE *tmp = malloc(sizeof(struct NODE));
if (tmp == NULL) {
printf("malloc failed!\n");
return -1;
}
scanf(
"%d %s %f %f %f",
&tmp->data.sno,
tmp->data.name,
&tmp->data.scores[0],
&tmp->data.scores[1],
&tmp->data.scores[2]
);
if (tmp->data.sno > 99999999) {
printf("sno is too long!\n");
return -1;
} else if (tmp->data.sno < 10000000) {
printf("sno is too short!\n");
return -1;
}
tmp->data.sum = tmp->data.scores[0] + tmp->data.scores[1] + tmp->data.scores[2];
tmp->data.average = tmp->data.sum / 3;
if (head == NULL || tmp->data.sum > head->data.sum) {
tmp->next = head;
head = tmp;
} else {
//插入时按总分从大到小排序
struct NODE *p = head;
while (tmp->data.sum <= p->data.sum && p->next != NULL) {
p = p->next;
}
tmp->next = p->next;
p->next = tmp;
}
}
FILE *fp = fopen("student.dat", "wb+");
if (fp == NULL) {
printf("File open failed!\n");
return -1;
}
struct NODE *p = head;
while (p != NULL) {
fwrite(&p->data, sizeof(struct student), 1, fp);
printf(
"%d %s %.2f %.2f %.2f %.2f %.2f\n",
p->data.sno,
p->data.name,
p->data.scores[0],
p->data.scores[1],
p->data.scores[2],
p->data.sum,
p->data.average
);
p = p->next;
}
return 0;
}

malloc 前面强转一下
(struct NODE*)malloc