C에서 내 프로그램에 문제가 있습니다.이 함수 create_class_list
는 입력 파일에서 학생의 ID를 읽고 학생 목록을 저장하는 데 필요한 메모리를 동적으로 할당하고 학생의 ID를 초기화해야합니다.
더 구체적으로:
student
.student
.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;
}
그리고 출력은 입력 파일의 첫 번째 학생 #이어야합니다. 프로그램이 컴파일되지만 충돌이 발생합니다.
한 줄을 변경해야합니다.
fscanf(input_file,"%d", &students[i].ID);
fscanf
의 인수는 포인터 이기 때문 입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다