-1
我在C程序中遇到了一些問題。函數create_class_list
應該從輸入文件讀取學生的ID,動態分配存儲學生列表所需的內存並初始化學生的ID。C中的動態結構和指針
更具體地:
- 分配指針數組以
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 [...] crashes_對您的問題沒有如此精確的描述。這不是我code_的網站_plz d錯誤。它在哪裏崩潰? – GingerPlusPlus 2014-11-02 21:27:50
@GingerPlusPlus我會猜測段落 – 2014-11-02 21:30:13