我遇到了一個問題,我嘗試使用函式在結構中添加鏈表。編譯器說我正在使用一個 NULL 指標。我不確定究竟是什么原因造成的,感謝任何幫助,謝謝!
我有 2 個結構:struct student 和struct school
結構學生:
struct student{
char student_name[STR_MAX];
double grade;
struct student *next;
};
結構學校
struct school {
struct student *students;
}
有問題的功能
我正在嘗試將學生的鏈表添加到學校,這有點像結構中的鏈表。我不確定為什么它不起作用。編譯器說我試圖通過空指標訪問一個欄位,我在它所在的位置添加了注釋。
int add_student(
struct school *school
char student_name *student_name,
double grade,
) {
struct student *new_student = malloc(sizeof(struct student));
new_student->grade = grade;
strcpy(new_student->student_name, student_name);
new_student->next = NULL;
struct student *current = school->students;
//Adding the first linked list
if (current == NULL) {
school->students= new_student;
}
//others
while (current->next != NULL) { //the compiler pointed here
current = current->next;
}
current->next = new_student;
new_student->next = NULL;
return 1;
}
另外,我還有另一個功能,我不確定是否對此有任何用處,它只是將記憶體分配給學校。我不確定它是否有用。
struct school *new_school() {
struct school *new = malloc(sizeof(struct school));
new->students = NULL;
return new;
}
uj5u.com熱心網友回復:
Paserby 指出了這個問題,但我也會把它放在這里。在 if 陳述句中,如果沒有學生,則將學生鏈接串列的頭部指向新學生
//Adding the first linked list
if (current == NULL) {
school->students= new_student;
}
但是你繼續往下看。Current 仍將為 null,因為它是創建時存盤在 school->students 中的值的副本
//others
while (current->next != NULL) { //the compiler pointed here
current = current->next;
}
將 while 回圈放在 else 陳述句中或在 if 陳述句中重新分配 current
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/357616.html
上一篇:structNode*ptr=malloc(sizeof(*ptr))如何作業?
下一篇:使用C中的指標將2個矩陣相乘
