我正在尝试创建程序来构建链接列表,但是在创建第二个错误时它会给我一个分段错误。
[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", ¤t->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]#
答案 0 :(得分:5)
您永远不会初始化next
所以行
current = current->next;
将当前值更改为指向未初始化的内存。您还需要为循环的每次迭代分配一个新的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);
}
}
答案 1 :(得分:0)
除了simonc所说的(这是正确的)之外,您应该将next
设置为循环中的某些内容。