Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 链表程序在生成下一个节点时崩溃_C - Fatal编程技术网

C 链表程序在生成下一个节点时崩溃

C 链表程序在生成下一个节点时崩溃,c,C,我试图创建程序来构建链表,但它在创建第二个错误时给了我一个分段错误 [root@vmc#u prog]#vi link1.c #include <stdio.h> #include <stdlib.h> struct node { int x; struct node *next; }; int main () { int d; struct node *root;

我试图创建程序来构建链表,但它在创建第二个错误时给了我一个分段错误

[root@vmc#u prog]#vi link1.c

#include <stdio.h>
#include <stdlib.h>


struct node {

        int x;
        struct node *next;
        };

int main () {

        int d;
        struct node *root;
        struct node *current;



        root = malloc(sizeof(struct node));

        current = root;

        printf ("Location of root is %p \n", root);

d = 1;
while (d>0){

        printf ("Enter the value of X: ");
        scanf ("%d", &current->x);

        printf ("value of x is stored\n");
        printf ("Location of current is %p \n", current);
        printf ("Value of X in 1st node: %d\n", current->x);

        current = current->next;


        printf ("Enter zero to terminate the loop: ");

        scanf ("%d",&d);

        }

}

您从不初始化
next
,因此该行

current = current->next;
将当前更改为指向未初始化的内存。您还需要为循环的每个迭代分配一个新的
节点

下面的代码应该可以正常工作。(它可以简化;我已经尽力使它尽可能接近您的代码。)


您从不初始化
next
,因此该行

current = current->next;
将当前更改为指向未初始化的内存。您还需要为循环的每个迭代分配一个新的
节点

下面的代码应该可以正常工作。(它可以简化;我已经尽力使它尽可能接近您的代码。)


除了simonc所说的(这是正确的),您可能还应该将
next
设置为循环中的某个内容

除了simonc所说的(这是正确的),您可能还应该为循环中的某个内容设置
next

int main () {
    int d;
    struct node *root = NULL;
    struct node *current;
    d = 1;
    while (d>0){
        printf ("Enter the value of X: ");
        scanf ("%d", &d);
        if (root == NULL) {
            root = calloc(1, sizeof(struct node));
            current = root;
            printf ("Location of root is %p \n", root);
        }
        else {
            current->next = calloc(1, sizeof(struct node));
            current = current->next;
        }
        current->x = d;

        printf ("value of x is stored\n");
        printf ("Location of current is %p \n", current);
        printf ("Value of X in last node: %d\n", current->x);

        printf ("Enter zero to terminate the loop: ");

        scanf ("%d",&d);

        }
}