Home > Software design >  linked list always NULL
linked list always NULL

Time:12-19

I have some beginners question in C, I am trying to insert into a linked list some nodes but it's always null. I am unable to change the global variable of booklist. Here's the following code

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

CodePudding user response:

You goal here is that when newBook is called for the first time, book_ref should have an address pointing to the first element of the list.

When you need to modify a pointer, you need to pass in the address of the pointer. In this case, you need to pass the address of book_ref to the newBook function which now has to work with a pointer to a pointer:

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

}
  • Related