0

リンクリストを作成するプログラムを作成しようとしていますが、2番目の障害を作成しているときにセグメンテーション違反が発生します。

[root @ vm c_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);

        }

}

[root@vm c_prog]# ./a.out 
Location of root is 0xc34b010 
Enter the value of X: 3
value of x is stored
Location of current is 0xc34b010 
Value of X in 1st node: 3
Enter zero to terminate the loop: 5
Enter the value of X: 5
Segmentation fault
[root@vm c_prog]# 
4

2 に答える 2

5

あなたは決して初期化nextしないので、行

current = current->next;

current を初期化されていないメモリを指すように変更します。nodeまた、ループの反復ごとに新しいものを割り当てる必要があります。

次のコードは、ほぼ機能するはずです。(単純化することもできます。できるだけコードに近づけるようにしています。)

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

        }
}
于 2013-02-07T18:19:35.533 に答える
0

simonc の言うことは別として (これは正しい)、おそらくnextループ内の何かにも設定する必要があります。

于 2013-02-07T18:25:34.113 に答える