我知道我可以更改代码来修复错误,但我不明白为什么会出现段错误。感谢所有帮助,谢谢。
typedef struct nodes{
int data;
struct nodes *next;
} node;
int main(int argc, char * argv[]){
node *head = NULL;
node *tmp = NULL;
int i;
head = malloc(sizeof(node));
tmp = head;
for(i = 0; i < 10; i++){
tmp->data = i;
tmp->next = malloc(sizeof(node));
tmp = tmp->next;
}
tmp = NULL;
for(tmp=head; tmp->next != NULL; tmp = tmp->next){
printf("%d\n", tmp->data);
}
}
这是输出:
0
1
2
3
4
5
6
7
8
9
0
Segmentation fault: 11
最佳答案
最后一个节点的next
指针未设置为null
。因此,第二个 for 循环中的条件 tmp->next != NULL 永远不会得到满足。事实上,您可以看到在段错误发生之前,在最后一个数字 (9
) 之后打印了一些垃圾数字 (0
)。
当你这样做时:
tmp->next = malloc(sizeof(node));
您还应该添加如下内容:
tmp->next->next = NULL;
通过这种方式,您可以“安全”地初始化每个节点,并将 next
指针设置为 NULL
。除最后一个节点之外的所有节点都将在下一次迭代中获得正确的值。
编辑 正如 @Someprogrammerdude 在评论中指出的,即使您按照上面的建议进行操作,您最终也会在最后得到一个额外的节点。 要解决这个问题,您可以按如下方式更改创建循环:
for(i = 0; i < 10; i++){
tmp->data = i;
if (i < 9) {
tmp->next = malloc(sizeof(node));
} else {
tmp->next = NULL;
}
tmp = tmp->next;
}
关于c - 不知道为什么我在这里遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620981/