如标题所示,我的代码给出了上述警告并混搭了内存引用。 我的任务是在 C++ 中使用嵌套类。这段代码主要是我以前的 C 应用程序的链接列表代码,但为 C++ 重新制作。 我已经在互联网上搜索过有关 NULL 异常的信息,但我无法弄清楚。 我会发布代码,希望有人能给我一些提示。 在 Internet 上的各种链接和提示中,它说我指向的指针正在引用 NULLptr,并且它不能访问 NULL 地址。 尝试以各种形式对其进行审查,但没有用。
标题
#ifndef LIST_H
#define LIST_H
#include <iostream>
#include <math.h>
using namespace std;
class List
{
private:
class Node {
public:
int data;
Node* next;
Node() {
this->data = NULL;
this->next = NULL;
}
};
Node* head;
public:
List();
void insertList(int data);
void deleteFromList(int data);
void deleteLowerThan(int lower);
void calculateArithmetic();
void showList();
};
#endif
Cpp文件
List::List() {
this->head = NULL;
}
void List::insertList(int n) {
Node* new_node = new Node();
new_node->data = n;
new_node->next = head;
head = new_node;
}
void List::deleteFromList(int n) {
Node* temp = head;
Node* prev = NULL;
if (temp != NULL && temp->data == n) {
head = temp->next;
return;
}
while (temp->data != n && temp != NULL) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
}
void List::deleteLowerThan(int n) {
Node* temp = head;
while (temp != NULL) {
if (temp->data < n) {
deleteFromList(temp->data);
}
else {
temp = temp->next;
}
}
}
void List::showList()
{
Node* temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
司机
int main() {
List lista;
lista.insertList(2);
lista.insertList(4);
lista.insertList(6);
lista.insertList(8);
lista.insertList(3);
lista.insertList(1);
lista.insertList(-4);
lista.showList();
lista.deleteFromList(4);
lista.showList();
lista.deleteFromList(8);
lista.showList();
lista.deleteFromList(6);
lista.showList();
lista.deleteLowerThan(3);
lista.showList();
return 0;
}
最佳答案
问题出在您的 deleteFromList
函数上,代码如下:
while (temp->data != n && temp != NULL) {
//...
在这里,您正在尝试检查 temp->data
的值 before 您已验证 temp
是 NULL
。因此,在某些时候(当你在列表的末尾时,temp
is NULL
将取消引用空指针- 这不好!
相反,只需颠倒比较的顺序:
while (temp != NULL && temp->data != n) {
//...
这样,一旦 temp
为 NULL
,比较结果将完全已知(参见 short circuiting),temp->data
将不 被评估,循环将停止运行。
关于c++ - 错误 C6011 :Dereferencing NULL pointer 'NAME' . C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58983393/