C++在链表中设置下一个节点指针

标签 c++ pointers

因此,我正在用 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,但它会抛出异常。抱歉,一开始非常含糊。

最佳答案

我们不知道allocateSetNext的具体实现。

如果没问题,请看这里:

if (first == NULL) 
{
    first = n;
    last = first; // You should assign last with the head node pointer.
}
...

也许有帮助。

关于C++在链表中设置下一个节点指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897111/

相关文章:

java - 将 Java 嵌入到 C++ 应用程序中?

C++ 将动态指针传递给二维数组

c - C 上的相同地址空间

c++ - 如何在Linux上写一段程序让CPU忙到一定程度?

c++ - 从标准输入捕获字符,无需等待按下 Enter 键

c++ - 如何实现平滑的切线空间法线?

pointers - 检查基础类型是否是具有反射的结构

c# - (DLLImport)尝试读取或写入 protected 内存。这通常表明其他内存已损坏

c++ - 为什么用点运算符的值在C++中没有更改?

c++ - 使用带有智能指针的 setter/getter