链表作为函数的参数

Lee*_*eet 0 c pointers linked-list

程序不会按预期打印列表的值.它打印的东西必须是一个内存地址imo.我一直试图找到独奏解决方案,但到目前为止无济于事.我将不胜感激.

#include <stdio.h>

typedef struct node
{
    int val;
    struct node * next;
} node_t;

void print_list(node_t * head);

void main()
{
    node_t * head = NULL;
    head = malloc(sizeof(node_t));
    if (head == NULL)
        return 1;
    head->val = 1;
    head->next = malloc(sizeof(node_t));
    head->next->val = 2;
    head->next->next = malloc(sizeof(node_t));
    head->next->next->val = 3;
    head->next->next->next = malloc(sizeof(node_t));
    head->next->next->next->val = 18;
    head->next->next->next->next = NULL;

    print_list(&head);
    system("pause");
}

void print_list(node_t * head) {
    node_t * current = head;

    while (current != NULL) {
        printf("%d\n", current->val);
        current = current->next;
    }
}
Run Code Online (Sandbox Code Playgroud)

由于您的输入,上述问题已得到解决.非常感谢你!但是,出现了一个新问题.想要在列表中添加新元素,我添加了几行代码.不幸的是,没有打印想要的结果,程序突然终止.这是新代码:

    head->next->next->next->next = malloc(sizeof(node_t));
    head->next->next->next->next->val = 5556;
    head->next->next->next->next->next = NULL;
    node_t * current = head;
    while (current->next != NULL) 
    {
        current = current->next;
    }
    current->next = malloc(sizeof(node_t));
    current->next->val = 32;
    current->next->next = NULL;
    printf("%d\n", current->next->val);
    system("pause");
}
Run Code Online (Sandbox Code Playgroud)

GAU*_*YAS 5

请注意,您的函数void print_list(node_t * head);需要一个类型的参数,node_t *但您传递的是类型参数node_t **.

更改print_list(&head);print_list(head);

head的类型为node_t *&head为型node_t **.