【发布时间】:2014-11-02 21:23:19
【问题描述】:
我的 C 程序存在一些问题。函数 create_class_list 应该从输入文件中读取学生 ID,动态分配存储学生列表所需的内存并初始化学生 ID。
更具体地说:
- 分配一个指向
student的指针数组。 - 为
student类型的每个变量分配内存。 - 将成员初始化为正确的 ID 值。
- 将数组中的每个指针设置为指向
student类型的变量。 - 返回指向
student的指针数组开头的指针。
这是我目前的代码:
我的结构学生:
typedef struct{
int ID;
int project_grade;
int exam_grade;
float course_mark;
struct student *student;
}student;
我的班级列表功能:
student **create_class_list( char *filename, int *sizePtr )
{
int i = 0;
student **StructPtr;
student *students;
FILE *input_file = fopen("IDnumbers.txt", "r"); //opens input file for reading
fscanf(input_file,"%d", sizePtr ); //scans the number of students from input file
StructPtr = (student**)calloc(*sizePtr, sizeof(student*)); // creates an array of pointers to student
student **original = StructPtr; // makes a pointer to the first element
students = (student*)calloc(*sizePtr, sizeof(student)); // creates an array of type student of 'x' students
while(i < *sizePtr){
StructPtr[i] = &students[i];
fscanf(input_file,"%d",students[i].ID ); //allocates IDs to all students
students[i].course_mark = 0; //initializes all grades to 0
students[i].exam_grade = 0; //initializes all grades to 0
students[i].project_grade = 0; // initializes all grades to 0
i++; // increments counter
}
fclose(input_file); //closes file
return original; //returns pointer to first element
}
还有我的主要测试功能:
int main()
{
int NumberStudents = 0; // number of students in class
int i; //counter variable
student **x;
x = create_class_list("IDnumbers.txt", &NumberStudents);
printf("%d\n",(**x).ID);
return 0;
}
输出应该是输入文件中的第一个学生#。程序编译,但崩溃:/ 有什么建议吗?
【问题讨论】:
-
program [...] crash 对您的问题的描述并不准确。这不是一个站点请检查我的代码。它在哪里崩溃?
-
@GingerPlusPlus 我猜是段错误