【问题标题】:Code has stopped working代码已停止工作
【发布时间】:2014-01-20 08:59:15
【问题描述】:

我在 DEV C++ 和 Code Blocks 测试过,结果是一样的。在控制台上,当我按下 Enter 按钮时,我看到“名称已停止工作”。

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>

using namespace std;

struct ll {
 int value;
 ll * next;
};

int main() {
  int n;
  ll a;
  cin>>n;
  a.value=n;
  ll cur;
  cur=a;
  // error is something here 
  while (n!=0){
    cin>>n;
    cur=*cur.next;
    cur.value=n;
  }
  //  has stopped working
  system("pause");
  return 0;
}

【问题讨论】:

  • 你的 cur 的 next 没有初始化,它可能包含几乎任何东西,它可能指向你不允许写入的内存部分。初始化你的变量!
  • system("pause")!!!我的眼睛在流血!

标签: c++ data-structures linked-list


【解决方案1】:

你没有为链表中的下一个节点分配内存。

int main(){
  int n;
  ll a;
  cin>>n;
  a.value=n;
  ll cur; // memory for the 2-member struct called ll is allocated on the stack here.

但在这里,您并没有为下一个对象分配新内存:

  while (n!=0){
    cin>>n;
    cur=*cur.next; // cur.next is null, or worse, undefined and refers to a random address.
    cur.value=n;
  }

在堆栈上分配链表的头部可以正常工作,但您至少需要为链表的其他元素找到内存。我建议在堆上分配所有内容。

以下是如何从堆中为每个附加节点分配内存:

  while (n!=0){
    cin>>n;
    cur.next = new ll();
    cur=*cur.next;
    cur.value=n;
  }

【讨论】:

  • @user3154916 - 查看我的编辑。虽然这会让您走得更远,但您应该了解堆内存与堆栈内存的工作原理、如何分配和释放内存以及如何确保不会泄漏内存等。C/C++ 具有非常具体的内存模型,可能会造成混淆。您应该花时间了解它们的工作原理。
  • 您可能想查看我最近关于堆栈与堆内存的回答。它是在 Java 工作原理的背景下编写的,但其中很多内容是普遍适用的。 stackoverflow.com/a/20833010/344638
  • malloc 行出现错误“从 'void' 到 'll*' 的有效转换”
  • @user3154916 - 我的错;我忘了这是c++。见编辑。我/你/我们需要从 malloc 中转换结果。
  • 非常感谢。我还有一个问题,在从控制台读取整数后,我写了 (ll i=a; i.next!=NULL; i=*i.next){ cout
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 2016-04-26
相关资源
最近更新 更多