C++ 结构指针隔离错误
C++ Struct Pointer Segfault
首先,提前感谢所有回复这篇文章的人。
其次,我浏览了所有其他帖子,找不到任何对我有帮助的东西(抱歉,我是C++新手)。
这是我的代码:
Node* Insert(Node *head,int data) //for linked lists
{
Node* current = head;
while(current -> next != NULL){
current = current -> next;
}
cout << head -> data;
Node *last = new Node();
last -> data = data;
last -> next = NULL;
current -> next = last;
return head;
}
似乎(通过行注释的反复试验)当前指针中下一个属性的访问似乎是问题所在,但我似乎无法弄清楚原因。Node 结构有两个属性,*next(指向链表中的下一项)和数据(节点的数据)。
对正在发生的事情有什么想法吗?
Linuxuser
编辑:问题解决了 - 非常感谢所有发表评论的人!
可悲的是,我无法使用**pHead
取消引用解决方案,因为问题出在自动输入函数参数的网站上。但是,使用下面的评论,我制作了一个简单的程序,我希望它能为像我这样的其他初级C++程序员详细介绍这个问题:
Node* Insert(Node *head,int data)
{
if(head == NULL){
Node* last = new Node();
last -> data = data;
return last;
}
Node *current = head;
while(current -> next != NULL){
current = current -> next;
}
Node *last = new Node();
last -> data = data;
last -> next = NULL;
current -> next = last;
return head;
}
问候
Linuxuser
这里最可能的问题是你不能使用Insert
来"快速启动"你的列表:如果head
开始NULL
,循环将立即失败。此外,在第一次插入时,您将无法分配head
。
若要解决此问题,请将第一个参数从 Node *head
更改为 Node **pHead
,传递指向头指针的指针,并向 Insert
函数的代码添加额外的取消引用级别:
Node* Insert(Node **pHead, int data)
{
while(*pHead != NULL){
pHead = &((*pHead)->next);
}
Node *last = new Node();
last -> data = data;
last -> next = NULL;
*pHead = last;
return last;
}
请注意,即使您将指针传递到设置为 NULL
的指针Node
此方法也将起作用:
Node *head = NULL;
Insert(&head, 1);
Insert(&head, 2);
Insert(&head, 3);
相关文章:
- 从矢量中删除元素后出现隔离错误
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 线程时访问静态映射时出现隔离错误
- 并行快速排序分区中的隔离错误
- C++多线程程序:变量定义为类成员的隔离错误
- TFLite 隔离错误,通过获取C++输入和输出
- 我只是在寻找模板,在我的书中找到了这段代码,这显示了隔离错误?
- pthread_create中错误 4 的隔离错误
- 递归树遍历/分支删除的隔离错误
- 在类模板上使用 arm gcc 编译期间的隔离错误
- 从大量文件读取时出现隔离错误
- 在PHP扩展中使用emalloc从线程时出现隔离错误
- 通过 Boost Python 在C++对象之间传递共享指针的隔离错误
- 在QT中单击菜单时出现隔离错误
- 尝试访问标头声明成员时出现隔离错误
- 搜索链表时出现隔离错误
- 模板化子类析构函数中的隔离错误
- 插件中节点.js/Nan 回调C++不频繁的隔离错误
- 将行添加到 GTKTreeView 时的隔离错误
- 找不到命令时打开的隔离错误