【问题标题】:Linked List "exception thrown" [closed]链表“抛出异常”[关闭]
【发布时间】:2020-02-11 17:06:29
【问题描述】:

我正在为学校开发这个链接列表程序,当我尝试运行我的程序时,我收到了一条消息,上面写着“抛出异常:读取访问冲突,学生为 nullptr”。这是我的主要功能是找到“学生”

int main() {
    ifstream datafile;
    list studentinfo;
    list::node *student = NULL;
    list::nodePtr head = NULL;
    list::node nodeinfo[10];

    datafile.open("Z:\\CS246\\Linked_List_Final\\studentdata.txt");
    if (!datafile)
    {
        cout << "Error!!";
        exit(1);
    }
    for (int i = 0; i < 10; i++) {
        datafile >> nodeinfo[i].name >> nodeinfo[i].id >> nodeinfo[i].gpa;
        studentinfo.addNode(&student, student->id);
    }
    list displayList(studentinfo);

    string choice, ans;
    int pos;

    cout << "Would you like to delete a node? If so type yes:";
    cin >> choice;
    if (choice == "yes" || choice == "Yes") {
        do {
            cout << "Type the postion of the node you would like to delete";
            cin >> pos;
            studentinfo.deleteNode(pos);
            cout << "Is there another node you would like to delete?";
            cin >> ans;
        } while (ans == "yes" || ans == "Yes");
    }

    system("pause");
    return 0;
}

如果我需要发布我的其余代码,请告诉我。

【问题讨论】:

  • 该代码中唯一使用学生的地方是studentinfo.addNode(&amp;student, student-&gt;id);,所以它必须在那个函数中?但建议您尝试在调试器下运行代码,它会显示问题发生的确切行
  • 看起来你有一个list 类。这个类应该做所有节点的管理。 main 更好的是它对 list::nodeheadlist::nodePtr 一无所知。所有main 都应该知道并有一个实例是list 有关原因的详细信息,请参阅教科书的封装部分。
  • 我从调试器得到这个错误,哈哈
  • @JoshuaMckinney 然后你应该在你的问题中添加调试器在哪一行指示错误以及你在调试会话中到目前为止所做的工作以确定问题的原因,以便其他人不要必须猜。

标签: c++ oop linked-list singly-linked-list


【解决方案1】:
    studentinfo.addNode(&student, student->id);

在这里,您尝试取消引用 student,即使它的值为 nullptr。在这样做之前,您需要为其分配一些值。也许您正在寻找nodeinfo[i].id

【讨论】:

  • 感谢我尝试了student = nodeinfo;,它成功了,但现在文件无法打开
【解决方案2】:
studentinfo.addNode(&student, student->id);

当您尝试访问它时 student 是否没有实例化 (->)?无法访问 nullptr。

【讨论】:

    【解决方案3】:

    您将学生指针设置为 null,然后尝试访问 student->id,但它只有 null 的值。

    【讨论】:

    • 当我将它设置为List::node *student;时,我不断收到错误
    【解决方案4】:
    List::node * student = NULL;
    ...
    student->id
    

    Null 取消引用。

    【讨论】:

    • 我该怎么做?
    • @JoshuaMckinney 我告诉你你做错了什么。您不能取消引用 NULL。另外,在你的代码中,为什么你有一个“链表”,还要创建一个array 的节点?你需要选择你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2014-01-17
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多