在stuct中使用双指针

在stuct中使用双指针,c,struct,double-pointer,C,Struct,Double Pointer,假设我定义了一个student结构: 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

假设我定义了一个student结构:

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;
    }
}
我想先将这个新的
插入
学生列表\u ptr

我这样做了,但它给了我一个分段错误。

在做任何事情之前,您必须纠正学生结构定义,如下所示:

struct student {
     struct student *next;
};
typedef struct student Student;
首先,您必须检查是否添加了第一个元素,然后将
学生列表\u 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\u list\u ptr
将为空。然后将其分配给当前
(现在也为空)并尝试取消引用。这是未定义的行为,也是导致崩溃的原因

如果总是将新学员添加到列表的前面,只需将新节点设为根节点,并将旧根节点指向它:

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,如果为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;
    }
}

请不要将
Student
Student
混用,仅使用其中一种以避免混淆,请修复代码。另外,将文本添加到问题中,而不是作为注释。您的
typedef
是否以这种方式工作?我觉得这是不对的。