【发布时间】:2016-12-26 21:25:26
【问题描述】:
大家好,我正在尝试通过 QT 中 cpp 中的程序编程来制作链表,每当我尝试向列表中添加内容时,我都会收到此错误:
c:\users\marcin\documents\dev cpp\proc_list\proc_list.cpp:11: error: Exception at 0x13fc325cb, code: 0xc0000005: write access violation at: 0x1, flags=0x0 (first chance)
从我已经阅读的内容来看,问题应该是我尝试访问空指针,但已经尝试检查它并且看起来不错。这是错误的代码:
void append_rec(QString name, int age, int number, float balance, item *first){
item *newrec;
item *temp;
newrec = new item(this);
temp = new item;
newrec->next = NULL;
newrec->name = name;
newrec->number = number;
newrec->balance = balance;
newrec->age = age;
temp = first;
while(temp->next!= NULL)
temp = temp->next;
temp->next = newrec;
}
还有问题(正如调试器所说,在newrec->next = NULL; 行中弹出。我刚刚开始学习 cpp,严重找不到解决方案。
编辑
项目结构的代码(对于这个作业,我不允许使用类):
#ifndef PROC_LIST_H
#define PROC_LIST_H
#include <qstring.h>
struct item{
item *next;
QString name;
int age;
int number;
float balance;
};
void append_rec(QString name, int age, int number, float balance, item * first);
void display_list( item * first );
#endif // PROC_LIST_H
编辑 2
主窗口文件涵盖了我对列表所做的所有事情。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "proc_list.cpp"
item *first = NULL;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_front_add_clicked()
{
append_rec(ui->name_edit->text(),
ui->age_edit->text().toInt(),
ui->accnum_edit->text().toInt(),
ui->balance_edit->text().toFloat(),
first);
}
【问题讨论】:
-
newrec->next 的 thw 类型是什么?你可以分享项目类的代码吗?
-
@t.m.是的,当然,完全忘记了:)
-
我不确定在c++中是不是这样,但是在c结构中,如果你本身使用结构的关键字,你应该将它显式地写为结构。我的意思是,写“struct item *next”而不是“item * next”。
-
如何创建
first项目?proc_list.cpp第 11 行究竟发生了什么?哦。等待。this在那时如何合法?另外,为什么不使用std::vector或QVector或QList? -
当
item结构没有这样的构造函数时,你为什么要调用newrec = new item(this);?
标签: c++ qt linked-list qstring