gpt4 book ai didi

c++ - 访问链表时出现Segmentation fault 11

转载 作者:行者123 更新时间:2023-11-28 02:57:14 24 4
gpt4 key购买 nike

我确定我搞砸了我的指示,或者可能是最初的 NULL , 但我想不通。

我正在尝试将链表写入文本文件:

write_out(node *ll){
ofstream out;
out.open("output.txt");
if (!out.is_open()) exit(EXIT_FAILURE);

cout << ll->value;

//stuff to write out
}

和:

struct node {
int value;
node *next;
}

但行cout << ll->value原因Segmentation fault: 11 ,我不明白为什么。

我已经注释掉了我实际写出来的代码,因为这无关紧要,问题显然是我(缺乏)对上述工作原理的理解。

我调用write_out(linkedlist)其中 node* linkedlist指向第一个节点。

这发生在:

read_in(node *ll){
ifstream data; //opened and checked open as above for out
int v;
ll = new node;
node *tmp = ll;
data >> tmp->value;
while(data >> v){
tmp->next = new node;
tmp = tmp->next;
tmp->value = v;
}
tmp->next = NULL; //thanks @sharth
}

肯定还没有离开ll = NULL

最佳答案

read_in(node *ll){

ll 是一个按值传递的参数。这意味着在 read_in 中对它的任何更改都只是本地的,在它之外没有任何影响。因此,在 read_in 完成后,指向列表头部的指针仍然是 NULL(假设这是您用来初始化指针的内容)。因此,使用 NULL 参数调用 write_out 会取消引用 NULL 指针,这将导致您的 SIGSEGV。

关于c++ - 访问链表时出现Segmentation fault 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21711537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com