在结构中使用双指针

Using double pointers in stuct

假设我定义了一个学生结构:

stuct student {
    struct Student *next;
};
typedef struct student Student

现在我有以下功能:

void add_student(Student **student_list_ptr) {
    Student *new_s;
    new_s = malloc(sizeof(Student));

    // I want to insert this first the new_s into the student_list_ptr
    // I did this but it gives me a segmentation fault
    Student *current = *student_list_ptr;
    if (current->next == NULL){
        current->next = new_s;
    }
}

我想先将 new_s 插入 student_list_ptr 我这样做了,但它给了我一个分段错误。

在进行任何操作之前,您必须按如下方式更正您的学生结构定义:

struct student {
     struct student *next;
};
typedef struct student Student;

首先,您必须检查是否添加了第一个元素,然后将 student_list_ptr 设置为指向它。

if (current == NULL) {
    *student_list_ptr = *new_s;
}

之后您必须在列表末尾添加您的元素,因此您必须:

// Find end of the list;
while (current->next != NULL);
current->next = new_s;

假设您这样调用您的函数:

Student *list = NULL;
...
add_student(&list);

当您将第一个元素添加到列表中时,*student_list_ptr 将为 NULL。然后将其分配给 current(现在也是 NULL)并尝试取消引用它。这是未定义的行为,也是导致崩溃的原因。

如果你总是把新同学放在列表的前面,只需将新节点设为根节点并将旧根节点指向它即可:

void add_student(Student **student_list_ptr) {
    Student *new_s;
    new_s = malloc(sizeof(Student));

    new_s->next = *student_list_ptr;
    *student_list_ptr = new_s;
}

另一方面,如果您想在最后添加,则首先需要检查根节点是否为 NULL,如果是,则将新节点设为根节点:

void add_student(Student **student_list_ptr) {
    Student *new_s;
    new_s = malloc(sizeof(Student));
    new_s->next = NULL;

    if (*student_list_ptr == NULL) {
        *student_list_ptr = new_s;
    } else {
        Student *current = *student_list_ptr;
        while (current->next != NULL){
            current = current->next;
        }
        current->next = new_s;
    }
}