链接列表抛出异常且未打印第一个节点

时间:2019-05-10 07:18:47

标签: c++ pointers

链接列表抛出异常 读取访问冲突 this-> cur是nullptr

int  y = 0;
cur = start;

do
{
    y++;
    cout << "**********************" << endl;
    cout << "  Node:" << y << endl;
    cout << "  Name:" << cur->name << endl;
    cout << "  Roll:" << cur->roll << endl;
    cout << "   Number:" << cur->number << endl;
    cout << "***********************" << endl;
    cur = cur->node;
} while (cur->node != NULL);//nullptr error

1 个答案:

答案 0 :(得分:0)

我猜你的算法是错误的:

int  y = 0;
cur = start;

do
{
    ....
    cur = cur->node;   // at the end of the list cur->node is NULL
} while (cur->node != NULL);  // and here you dereference the null pointer

您可能想要这个:

...
cur = start;

do
{
    ....
    cur = cur->node;
} while (cur != NULL)

甚至是这样:

...
cur = start;

while (cur != NULL)
{
    ....
    cur = cur->node;
}