引发异常:写访问冲突. temp 为 nullptr
Exception thrown: write access violation. temp was nullptr
我在else
语句中的insert()
函数中出现错误。
这是结构:
struct Node
{
int data;
Node* next;
};
Node* head = NULL;
这是函数:
void insert(int data)
{
Node* New = new Node();
if (head == NULL)
{
New->data = data;
head = New;
}
else
{
// down here where the error occured
Node* temp = new Node();
temp = head;
while(temp != NULL)
{
temp = temp->next;
}
temp->data = data;
temp->next = New;
}
}
你的循环:
while(temp != NULL)
当temp
等于nullptr
时终止(请注意,您最好在 C++ 中使用此常量而不是NULL
(,并且紧接着您取消引用temp
。此外,您没有任何理由将new
的结果分配给temp
并立即将其丢失下一行代码(导致内存泄漏(。并且您应该始终将data
分配给新项目,而不是temp
(假设是最后一个项目(您的逻辑应该是这样的:
void insert(int data)
{
Node* New = new Node();
New->data = data; // note you better do these 2 lines in constructor
New->next = nullptr;
if (head == nullptr)
{
head = New;
return;
}
Node* temp = head;
while( temp->next != nullptr ) // look for the last item
temp = temp->next;
temp->next = New;
}
相关文章:
- 如何在自删除后将对象设置为nullptr
- 如何取消对nullptr的屏蔽,返回正确的对象
- C++ - "!pointer"和"pointer == nullptr"的区别?
- 将指针设置为"nullptr"并不能防止双重删除?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 节点 *temp; 和节点 *tmp = 新节点之间的差异
- [temp.variadic]中关于包扩展实例化的措辞
- 为什么我的节点在我设置后被设置为 nullptr = 新节点?
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- wx通用目录控制错误"wxTheFileIconsTable was nullptr"
- 当设置为 const 变量时使用 nullptr
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 检查类方法中是否(此 == nullptr)
- C++98,但叮叮当当地说使用nullptr?
- 使用未声明的标识符'temp'
- 为什么调试器引发"read access violation. this was nullptr"异常?
- 引发异常:写访问冲突. temp 为 nullptr