C语言在struct中嵌套链表添加元素时出现空指针错误如何解决
问题根源
空指针报错触发在首次添加学生节点的场景:
当链表为空时,current 初始值为 NULL,你在if分支中仅修改了 school->students = new_student,但current变量本身仍为NULL,后续执行while (current->next != NULL)时,对NULL指针取成员next就直接触发了空指针访问。
同时你的逻辑还存在重复赋值、无错误校验的问题。
修正后的代码
int add_student( struct school *school, char *student_name, double grade ) { // 入参判空,避免非法访问 if (school == NULL || student_name == NULL) { return 0; } // 校验malloc返回值,避免内存分配失败触发崩溃 struct student *new_student = malloc(sizeof(struct student)); if (new_student == NULL) { return 0; } new_student->grade = grade; // 用strncpy+手动补结束符,避免姓名超长触发缓冲区溢出 strncpy(new_student->student_name, student_name, STR_MAX - 1); new_student->student_name[STR_MAX - 1] = '\0'; new_student->next = NULL; struct student *current = school->students; // 首个节点赋值后直接返回,不进入后续遍历逻辑 if (current == NULL) { school->students = new_student; return 1; } // 只有非空链表才执行遍历找尾逻辑 while (current->next != NULL) { current = current->next; } current->next = new_student; return 1; }
额外优化建议
- 你提供的
new_school函数也可以增加malloc返回值判空,避免分配失败返回野指针 - 如果后续需要频繁添加学生,可以给school结构体加尾指针,避免每次添加都遍历整个链表,提升性能
内容的提问来源于stack exchange,提问作者user15483444
相关产品推荐
相关产品推荐

