【发布时间】:2016-04-01 17:47:19
【问题描述】:
我有一个非常简单的链表,我想在它上面执行函数,但是当我运行我的代码时,我不断收到“根”节点上的读取访问冲突错误。
这是我得到的错误(我在出现错误的代码行之后发表了评论):
抛出异常:读取访问冲突。 根是 0xCCCCCCCC。 如果有这个异常的处理程序,程序可以安全地继续。
这是结构:
struct node {
int value;
node* link;
node(int val) {
link = NULL;
value = val;
}
};
首先我在主函数中初始化该链表,如下所示:
int main()
{
node *root;
addnode(root, 20);
addnode(root, 1);
addnode(root, 50);
node *curr;
for (curr = root; curr->link != NULL; curr = curr->link) { // I get error here
cout << curr->value << " ";
}
cout << endl;
cout << "Number of elements " << countlist(root) << endl;
getchar();
return 0;
}
调用的函数是(第一个添加节点,第二个计算列表中的节点数):
void addnode(node *&root, int val) {
if (root != NULL) { // I get error here
node *temp=new node(val);
temp->link = root;
root = temp;
}
else
root = new node(val);
}
int countlist(node *root) {
if (root != NULL) {
int count = 0;
do {
count++;
root = root->link;
} while (root->link != NULL); // I get error here
return count;
}
return 0;
}
我不断收到的错误出现在我在代码中的 cmets 中提到的行中。
【问题讨论】:
-
在循环之前说
root == 0x12345和root->next == NULL。您希望您的病情检查什么? -
root未初始化,但使用了其(随机、未初始化)值。 -
您的代码对我来说很好用。您能否提供有关重现此错误的更多信息?
-
如果
root->next==NULL它将进入循环,计数 1 然后变为 NULL,然后它应该停止遍历并且不给出错误,但根似乎仍然转到 NULL 并且仍然不退出
标签: c++ linked-list access-violation