You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:15:03