在stuct中使用双指针

时间:2016-02-14 20:11:05

标签: c struct double-pointer

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

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 我做了这个,但它给了我一个分段错误。

2 个答案:

答案 0 :(得分:1)

假设您按照以下方式调用您的函数:

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;
}

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

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;
    }
}

答案 1 :(得分:0)

在此之前,您必须更正您的学生结构定义,如下所示:

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;
相关问题