代码已停止工作

时间:2014-01-02 20:10:31

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

我在DEV C ++和代码块测试了它,结果是一样的。在我按下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;
}

1 个答案:

答案 0 :(得分:4)

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

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;
  }