【问题标题】:Pointer causes access violation指针导致访问冲突
【发布时间】:2014-01-13 20:00:36
【问题描述】:

我有一个控制台应用程序从控制台读取一些字符数据,然后放入一个结构中。这个结构用作链表,当它被构造时,我保留一个指向第一个列表元素的指针和一个用于遍历列表的指针。 发生在我身上的是,当我第一次运行我的列表并将其内容写入控制台时,一切正常。当我稍后想将我的运行指针设置为列表最后一个元素时,它不断崩溃并出现 c000005 访问冲突错误。 我会给你我代码中有趣的部分:

我的结构定义:

struct musikdaten {
    char interpret[150];
    char titel[150];
    struct musikdaten* next;
};

打印列表内容:

while (it != NULL) {
    cout << it->interpret << ": " << it->titel << "\n";
    cout << "next: " << it->next << "\n";
    it = it->next;
}

将“it”设置为列表的最后一个元素:

while (true) {
    if (it->next == NULL) {
        cout << "Assigning some memory...\n";
        it->next = new musikdaten;
        break;
    }
    else it = it->next;
}

但是,当列表包含两个以上的元素时,最后一部分会不断崩溃。 注意:当从控制台读取内容时添加新列表元素时,next 指针始终初始化为 NULL。

【问题讨论】:

  • what do you cout it-&gt;next, it-&gt;next 可以为空
  • 把空指针检查无处不在,甚至不只是在它上面->下一步,如果它不正确,写出消息。我似乎在这里找不到任何错误。

标签: c++ pointers


【解决方案1】:

您应该使用NULL 初始化next 成员以指示列表的结尾:

it->next = new musikdaten;
it->next->next = NULL;

或者添加一个默认构造函数:

struct musikdaten {
musikdaten() { next = NULL; /*TODO: init other members*/}     
char interpret[150];
char titel[150];
struct musikdaten* next;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多