链表总是 NULL

linked list always NULL

我有一些 C 语言的初学者问题,我试图将一些节点插入到链表中,但它始终为空。我无法更改 booklist 的全局变量。下面是代码

typedef struct bookInfo {
    int code;
    char titre[50];
    char auteur[50];
    char editeur[50];
    int date;
    struct bookInfo *next;
    struct bookInfo *prec;
} Book;

typedef Book *bookList; 
bookList book_ref;

void newBook(Book *bk, int val)
{
    Book *new_node = (Book *)malloc(sizeof(Book));
    Book *last = bk; 

    new_node->code = val;
    new_node->next = NULL;

    if (bk == NULL)
    {
        bk = new_node;
        return;
    }

    while (last->next != NULL)
        last = last->next;

    last->next = new_node;
    return;
}

int main()
{
    newBook(book_ref, 45);
    printf("%p\n",book_ref);
    newBook(book_ref, 42);
    printf("%p",book_ref);
}

你的目标是当第一次调用 newBook 时,book_ref 应该有一个指向列表第一个元素的地址。

当你需要修改一个指针时,需要传入指针的地址。在这种情况下,您需要将 book_ref 的地址传递给 newBook 函数,该函数现在必须使用指向指针的指针:

typedef struct bookInfo
{
    int code;
    char titre[50];
    char auteur[50];
    char editeur[50];
    int date;
    struct bookInfo *next;
    struct bookInfo *prec;
} Book;

typedef Book *bookList;
bookList book_ref;

void newBook(Book **bk, int val)
{
    Book *new_node = malloc(sizeof(Book));
    Book *last = *bk;

    new_node->code = val;
    new_node->next = NULL;

    if (*bk == NULL)
    {
        *bk = new_node;
        return;
    }

    while (last->next != NULL)
        last = last->next;

    last->next = new_node;
    return;
}

int main(void)
{
    newBook(&book_ref,45);
    printf("%p\n",(void *) book_ref);
    newBook(&book_ref,42);
    printf("%p\n",(void *) book_ref);

    printf("%d\n", book_ref->next->code);

}