【问题标题】:C: Adding linked list inside struct results in null errorC:在struct中添加链表导致null错误
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 非常感谢,如果你看到了请忽略我之前的评论:D
猜你喜欢
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 2017-03-07
  • 2013-11-21
相关资源
最近更新 更多