在C中动态创建链接列表

Ati*_*esh -1 c struct linked-list

我正在尝试c使用结构动态创建链接列表并打印它.但我的下面的代码是抛出运行时错误可以任何人告诉我为什么我收到此错误.这是我的代码.

#include <stdio.h>
struct cnode
{
    int value;
    struct cnode *next;
};

void print_list(struct cnode* start)
{
    while(start->next != NULL)
    {
        printf("%d->", start->value);
        start = start->next;
    }
}

int main(void)
{
    int i,n,val;
    //List length
    scanf("%d", &n);

    //Head
    struct cnode* start;
    scanf("%d", &val);
    start->value = val;

    struct cnode* temp = start;

    for (i=1; i<=n-1; i++)
    {
        struct cnode* node;
        scanf("%d", &val);
        node->value = val;

        temp->next = node;
        temp = node;
    }
    temp->next = NULL;

    print_list(start);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 6

你没有为要指向的指针分配内存.你需要打电话malloc来做那件事.

struct cnode *start = malloc(sizeof(struct cnode));
if (start == NULL) {
    perror("malloc failed");
    exit(1);
}

...

struct cnode *node= malloc(sizeof(struct cnode));
if (node == NULL) {
    perror("malloc failed");
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)

此外,打印列表时,您不打印最后一个值.

while(start != NULL)
{
    printf("%d->", start->value);
    start = start->next;
}
Run Code Online (Sandbox Code Playgroud)

完成后不要忘记释放记忆.

print_list(start);

while (start != NULL) {
    temp = start;
    start = start->next;
    free(temp);
}

return 0;
Run Code Online (Sandbox Code Playgroud)