因此,我正在用 C++ 重新创建一个 LinkedList
,并且我试图将指针更改为指向我列表中的最后一个 Node
。这是我重载的 +=
运算符,所有魔法和错误都在这里发生。我有两种不同的方法来更改指针,但都在 Lab3.exe 中的 0x00ee42f3 处抛出 Unhandled exception: 0xC0000005: Access violation writing location 0xccccccec.
。这是怎么回事,我该如何解决?
void MyLinkedList::operator+=(const std::string& s)
{
allocator<Node> a;
Node* n = a.allocate(1);
a.construct(n, s);
if (first == NULL)
first = n;
else
{
(*last).next = n; // crashes here
(*last).SetNext(n); //also will crash here, if the previous statement is removed
last = n;
}
}
为了进一步说明,它将遍历并设置第一个Node
,退出该方法,下次调用时将运行并进入else
语句。此时有第二个Node
,它在内存中分配并实例化。我想要做的是将第一个 Node
中的 Node* next
指针设置为这个新的 Node
,但它会抛出异常。抱歉,一开始非常含糊。
最佳答案
我们不知道allocate
和SetNext
的具体实现。
如果没问题,请看这里:
if (first == NULL)
{
first = n;
last = first; // You should assign last with the head node pointer.
}
...
也许有帮助。
关于C++在链表中设置下一个节点指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897111/