名为readStudents的函数应该:
文件格式如下:
Name Surname ID Grade
Name Surname ID Grade
...
我执行的任务是:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char firstName[30], secondName[30];
int ID;
int grade;
} student;
student *readStudents(char *fileName, int* entry_size, int all_ids[], int* studentSize){
/*
all_ids is an array for counting the amount of grades per student. studentSize is the actual number of students (for example, in students1.txt it is 2)
*/
FILE *openedFile = fopen(fileName, "r");
if(openedFile == NULL){
printf("A problem occured with opening of file");
return 0;
}
char entrySize[10];
fscanf(openedFile, "%[^\n]", entrySize);
int numberOfEntries = atoi(entrySize);
*entry_size = numberOfEntries;
int i;
student *students[i];
*students = malloc(numberOfEntries * sizeof *students);
for(i=1; !feof(openedFile); i++){
fscanf(openedFile, "%s %s %i %i", students[i]->firstName, students[i]->secondName,
&(students[i]->ID), &(students[i]->grade));
}
return students;
}
int main(){
int entrySize = 0;
int allIds = 0;
int studentSize = 0;
student *studentsArray[entrySize];
*studentsArray = readStudents("students1.txt", &entrySize, &allIds, &studentSize);
int k;
for(k=0; k<entrySize; k++){
printf("%s %s %i %i \n", studentsArray[k]->firstName, studentsArray[k]->secondName, studentsArray[k]->ID, studentsArray[k]->grade);
}
}
编译并运行它后,它显示“分段错误:11”。
答案 0 :(得分:0)
应该使用指针而不是指针数组。
malloc
将为可以使用数组表示法[i]
访问的结构数量分配内存。
feof
通常不能很好地读取文件。而是将循环限制为分配的结构数,并确保fscanf可以读取4个项目。
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char firstName[30], secondName[30];
int ID;
int grade;
} student;
student *readStudents(char *fileName, int* entry_size, int *all_ids, int* studentSize){
/*
all_ids is an array for counting the amount of grades per student. studentSize is the actual number of students (for example, in students1.txt it is 2)
*/
FILE *openedFile = fopen(fileName, "r");
if(openedFile == NULL){
perror ( fileName);
exit ( 0);
}
char entrySize[10];
fscanf(openedFile, " %9[^\n]", entrySize);
int numberOfEntries = atoi(entrySize);
*entry_size = numberOfEntries;
int i;
student *students;
if ( NULL == ( students = malloc(numberOfEntries * sizeof *students))) {
perror ( "malloc students");
exit ( 0);
}
for(i=0; i < numberOfEntries; i++){
if ( 4 != fscanf(openedFile, "%29s %29s %d %d"
, students[i].firstName
, students[i].secondName
, &students[i].ID
, &students[i].grade)) {
exit ( 0);
}
}
fclose ( openedFile);
return students;
}
int main(){
int entrySize = 0;
int allIds = 0;
int studentSize = 0;
student *studentsArray;
studentsArray = readStudents("students1.txt", &entrySize, &allIds, &studentSize);
int k;
for(k=0; k<entrySize; k++){
printf("%s %s %d %d \n"
, studentsArray[k].firstName
, studentsArray[k].secondName
, studentsArray[k].ID
, studentsArray[k].grade);
}
free ( studentArray);
}