简体   繁体   English

C++ 中链表的读取访问冲突

[英]Read access violation on Linked List in C++

I have a very simple linked list that I want to perform functions on, but I keep getting the read access violation error on the 'root' node when I run my code.我有一个非常简单的链表,我想对其执行函数,但是当我运行我的代码时,我一直在“根”节点上收到读取访问冲突错误。

Here is the error I get (I commented after the lines of code I get the errors in):这是我得到的错误(我在收到错误的代码行之后进行了评论):

Exception thrown: read access violation.抛出异常:读取访问冲突。 root was 0xCCCCCCCC.根是 0xCCCCCCCC。 If there is a handler for this exception, the program may be safely continued.如果有这个异常的处理程序,程序可以安全地继续。

This is the struct:这是结构:

struct node {
int value;
node* link;

node(int val) {
    link = NULL;
    value = val;
}
};

First I initialize that linked list in main function like this:首先,我在 main 函数中初始化该链表,如下所示:

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;
}

And the function that are called are (first one to add nodes, and the second to count the number of nodes in the list):调用的函数是(第一个添加节点,第二个计算列表中的节点数):

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;
}

The error I keep getting are in the lines that I mentioned in the comments in the code.我不断收到的错误在我在代码注释中提到的行中。

A good habit to avoid this kind of problem might be initializing all variables at declaration:避免此类问题的一个好习惯可能是在声明时初始化所有变量:

int main() 
{
   node *root = nullptr;
   // ...
}

Also, you do not want:此外,您不希望:

node *curr;
for (curr = root; curr->link != NULL; curr = curr->link) {
    cout << curr->value << " ";
}

but

for (node *curr = root; curr != nullptr; curr = curr->link) {
    cout << curr->value << " ";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM