#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int id;
char *name;
char *lastname;
} student_type;
typedef struct
{
student_type list[15];
} student_list_type;
void get_students(FILE *input,char *filename,student_list_type *student_list);
int main()
{
printf("Hello world!\n");
student_list_type std_list;
student_list_type *std_list_p=&std_list;
FILE *input;
get_students(input,"students.txt",std_list_p);
return 0;
}
void get_students(FILE *input,char *filename,student_list_type *student_list)
{
int i=0;
int j=0;
input=fopen(filename,"r");
printf("filename is %s",filename);
while(fscanf(input,"%d",&student_list->list[i].id)==1)
{
student_list->list[i].name=(char *) malloc(15);
student_list->list[i].lastname=(char *) malloc(15);
fscanf(input,"%s",student_list->list[i].name);
fscanf(input,"%s",student_list->list[i].lastname);
i++;
}
for(j=0; j<i+1; j++)
{
free(student_list->list[i].name);
free(student_list->list[i].lastname);
}
free(student_list->list);
fclose(input);
}
我认为我在释放部分代码方面失败了。我知道我应该先释放元素然后整个数组,但我可能学错了方法。无论如何,这段代码不会给出错误消息,但有时会在获取所有学生列表后崩溃文本。