在 "CodePad" 中执行链表操作时转储的核心(这是一个在线C++编译器)
Core dumped while performing linked list operation in "CodePad" (which is an online C++ compiler)
最近我一直在练习一些链表编码问题。我刚开始使用unordered_set。问题是,"编写代码以从未排序的链表中删除重复项"。我为此使用了unordered_set。但是当我尝试初始化链表时,我遇到了"核心转储"的问题。
当我注释掉填充列表的最后 3 行时,它会显示数组。当我尝试在填充列表中访问头部时,它会显示核心转储。
这是我编写的整个代码。我已经在代码板网站上写了这个。
#include <iostream>
#include<vector>
#include<string.h>
#include<math.h>
#include<sstream>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<unordered_set>
using namespace std;
struct Node
{
int data;
Node *next;
};
Node *head=NULL;
void populateList(Node *head)
{
int arr[]={7,1,2,3,4,5,4,3,5,7,3,9,3,7,3,6,2,5,7,4};
cout<<"nn";
int n=sizeof(arr)/sizeof(int);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
Node *ptr=head;
如果我注释掉下面 for 循环中的内容,一切都运行顺利。
for(int i=0;i<n;i++)
{
ptr->data=arr[i];
ptr->next=NULL;
ptr=ptr->next;
}
}
int main()
{
Node *ptr=head, *prev=head;
populateList(head);
unordered_set<int> A;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
}
while(ptr!=NULL)
{
if(A.find(ptr->data)==A.end())
{
A.insert(ptr->data);
}
else
{
prev->next=ptr->next;
delete ptr;
ptr=prev->next;
}
prev=ptr;
ptr=ptr->next;
}
ptr=head;
cout<<"nn";
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
}
return 0;
}
问题是在你的 for 循环中,你在 NULL 旁边设置,然后尝试在下一次迭代时取消引用它
for(int i=0;i<n;i++)
{
ptr->data=arr[i];
ptr->next=NULL; // now ptr->next is NULL
ptr=ptr->next; // ptr = ptr->next = NULL;
}
如果你展开这个
int i = 0;
ptr->data=arr[0];
ptr->next=NULL;
ptr=ptr->next; // ptr = ptr->next = NULL;
i++;
// because we set ptr to NULL this is dereferencing the NULL pointer
ptr->data=array[1];
...
相关文章:
- C++,我收到一个无法理解的编译器错误
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 为什么 MSVC C++编译器将一个简单的 Hello World 扩展为 4000 行汇编?
- 在另一个编译器中打印乱码的数组 |C++
- 一个C++编译器是为不同的平台(Linux,Windows等)多次编写的,这是真的吗?
- Qt 5测试版2,Qt Creator 2.6,MSVC错误:Qt Creaator需要一个编译器来构建.在工具包选项中
- 为什么当我通过引用传递数组时,我会收到一个编译器错误,指出我的变量未定义
- 我能否获得一个C++编译器在编译时实例化对象
- 我有编译器的情况。当我运行代码来去除一串特殊字符时,它在一个编译器中运行,但在另一个编译器中不运行?
- 我认为这是一个编译器错误,这不应该影响我的代码,但它是
- 一个编译器中的运算符优先级不同,为什么
- 有符号整数溢出为负数:这是一个编译器错误,还是我误解了优化
- Bjarne 对这个 ADL 示例的看法是错误的,还是我有一个编译器错误
- 为什么不可能构建一个编译器来确定C++函数是否会更改特定变量的值
- QT需要建立一个编译器
- 我需要破解一个c++编译器来发出和解释一个特定的类指针作为全局数组内的索引
- 为什么一个C程序编译并链接到一个C编译器,然后在运行时SIGILL
- sizeof可以应用于未捕获的变量的lambda内部吗?还是这是一个编译器错误?
- 为什么这是一个编译器错误?(g + +)