Ahm*_*nis -1 c++ pointers linked-list
假设我有一个链表类,如下所示。
struct Node {
int data;
Node* rptr;
};
class LinkedList
{
public:
Node* curr;
Node* prev;
Node* first;
Node node;
LinkedList()
{
curr = NULL;
prev = NULL;
first = NULL;
node.data = NAN;
node.rptr = NULL;
}
void push(int);
void pop();
};
void LinkedList::push(int data)
{
curr = new Node;
curr->data = data;
curr->rptr = NULL;
if (first == NULL)
{
prev = first = curr;
}
else
{
prev->rptr = curr;
curr->data = data;
prev = curr;
}
}
void LinkedList::pop()
{
Node* temp = NULL;
if (first == NULL)
{
cout << "No more Data Element\n";
}
else
{
cout << first->data<<'\n';
temp = first;
first = first->rptr;
cout << first->rptr << endl;//error on this line
delete temp;
}
}
Run Code Online (Sandbox Code Playgroud)
我的主要内容如下
int main()
{
LinkedList l1;
l1.push(10);
l1.push(20);
l1.push(30);
l1.pop();
l1.pop();
l1.pop();
l1.pop();
l1.pop();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是当我尝试用 NULL 打印地址时,它给了我一个例外。有什么办法可以打印它,因为它可以很好地打印其他地址,但不是这个 NULL 地址。
如果我们将 None 分配给某物并打印它,我们可以很容易地在 Python 中看到。那么 C++ 是否具有相同的特性?
这里的问题是,您没有尝试打印 a nullptr,但您访问它并想要打印结果。在打印结果之前,您的程序已经有一个与打印完全无关的空指针异常。
first = first->rptr;
Run Code Online (Sandbox Code Playgroud)
first是一个有效的指针(不是 nullptr),您first现在分配rptr. 在你的情况下,该值first->rptr是nullptr。
如果您first->rptr再次尝试,您希望从第一个指向不可能的位置获取值。
您已经在first有效之前检查过(不是 nullptr ),但是在获得新值之后,您没有。
顺便说一句:如果要为指针分配“0”或与此进行比较,则应使用nullptr而不是NULL。