【发布时间】:2021-12-26 16:55:44
【问题描述】:
我遇到了一个问题,我尝试使用函数在结构内添加链表。编译器说我使用的是 NULL 指针。不知道是什么原因造成的,希望大家帮忙,谢谢!
我有 2 个结构:struct student 和 struct school
结构学生:
struct student{
char student_name[STR_MAX];
double grade;
struct student *next;
};
建立学校
struct school {
struct student *students;
}
有问题的函数
我正在尝试将学生的链接列表添加到学校,这有点像结构中的链接列表。我不确定为什么它不起作用。编译器说我试图通过 Null 指针访问一个字段,我已经在它的位置添加了注释。
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;
}
【问题讨论】:
-
请注意,您在 if 语句中检查是否
current == NULL,然后在下一个 while 语句中允许可能的空指针取消引用。 -
那么,如果我在 if 语句中使用 else 语句并包含 while 循环,它应该可以解决问题吗?
标签: c struct linked-list insert