gpt4 book ai didi

c++ - 链表内存读取错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:26:56 27 4
gpt4 key购买 nike

我正在尝试创建一个链表,但我有一个关于内存访问的问题。我调试代码,查看它在哪里出错,但无法解决。使用'Add watch',可以看到next has unable to read memory error.

struct Node
{
string Name;
Node* next;
};

struct LinkedList
{
Node* head = NULL;
bool isX = true;
};


LinkedList* initX(string Arr)
{
LinkedList* link = new LinkedList;
for (int i = 0; i < 15; i++)
{
Node* temp = new Node;
temp->Name = Arr[i];
Node* ptr = new Node;
ptr = link->head;
if (link->head != NULL)
{
while (ptr->next)
{
ptr = ptr->next;
}
ptr->next = temp;
temp->next = NULL;
}
else
link->head = temp;
}
return link;
}
Unhandled exception at 0x008E8AF7 in ...exe: 0xC0000005: Access violation reading location 0xCDCDCDE9.

我该如何解决?

最佳答案

if 语句的 else 部分将 link->head 设置为 temp 后,您不要将 temp->next 设置为 NULL,因此对 temp->next 的任何使用就好像它在未定义行为中具有值一样.将此添加到您的 else 部分:

else {
link->head = temp;
temp->next = NULL; // or nullptr
}

实际上,如果您移动两个 temp->next = NULL,将它们合并为一个,并将其作为 for 循环中的最后一条语句,实际上会更好。这就是为什么您不必为这两种情况做同样的事情。

关于c++ - 链表内存读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26349194/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com