2017-09-28 126 views
0

我做了一些代码,以了解链接列表如何在C++中工作,并且在程序终止之前它说错误“退出非零状态”。我目前使用在线编译器repl.it来测试C++代码,我不确定这个问题是否相关。我如何解决它?这是我的代码。详细详细详细详细细节细节细节细节细节细节细节细节细节细节细节细节详情详情退出非零状态(repl.it)C++?

#include <iostream> 
#include <string> 
using namespace std; 
struct node{ 
    int data; 
    node* next; 
}; 

int main() 
{ 
    node* n; //new 
    node* t; //temp 
    node* h; //header 

    n=new node; 
    n->data=1; 
    t=n; 
    h=n; 

    cout <<"Pass 1"<<endl; 
    cout <<"t=" << t << endl; 
    cout <<"n=" << t << endl; 
    cout <<"h=" << h << endl; 
    cout << n->data << endl; 

    n=new node; 
    n->data=2; 
    t->next=n; 
    t=t->next; 

    cout <<"Pass 2"<<endl; 
    cout <<"t=" << t << endl; 
    cout <<"n=" << t << endl; 
    cout <<"h=" << h << endl; 
    cout << n->data << endl; 


    n=new node; 
    n->data=3; 
    t->next=n; 
    t=t->next; 

    cout <<"Pass 3"<<endl; 
    cout <<"t=" << t << endl; 
    cout <<"n=" << t << endl; 
    cout <<"h=" << h << endl; 
    cout << n->data << endl; 

    //Test pass 
    //exits with non-zero status 
    //NULL to pointer means invalid address; termination of program? 

    n=new node; 
    t=t->next; 
    n->data=4; 
    t->next=n; 
    n->next=NULL; 

    cout <<"Pass 4"<<endl; 
    cout <<"t=" << t << endl; 
    cout <<"n=" << t << endl; 
    cout <<"h=" << h << endl; 

    string a; 
    a="End test"; 
    cout << a << endl; 

    return 0; 
} 

输出是

Pass 1 
t=0x12efc20 
n=0x12efc20 
h=0x12efc20 
1 
Pass 2 
t=0x12f0050 
n=0x12f0050 
h=0x12efc20 
2 
Pass 3 
t=0x12f0070 
n=0x12f0070 
h=0x12efc20 
3 
exited with non-zero status 
+2

检查*为了*在你做的事情在“传4”。您在那里取消引用未初始化的指针。将来请先使用调试器来发现这些问题。 –

+0

无论你的问题如何,不要使用'new'。每次使用'new'时,都会动态分配内存,您必须始终“删除”。可以使用'unique_ptr ',这是一个封装类,它在超出作用域时自动删除节点,或者给你的节点类添加一个'add_next'方法,在内部使用'new'并使'〜node'做'删除下一个'。在后面的例子中,你必须小心编写异常安全的代码,这就是为什么你应该更喜欢'unique_ptr'解决方案。 – patatahooligan

+0

你一直在'n ='行打印't'。太多的复制和粘贴? – molbdnilo

回答

1
n=new node; 
    t=t->next; <- error there 
    n->data=4; 
    t->next=n; 
    n->next=NULL; 

此时t是你创建的第三个节点,此时该节点没有任何价值的是next属性。

您可以使用调试器GDB看更容易这样那样的问题(但也许在您的在线编译器,你可以不)

+0

有道理,谢谢! – user136128

相关问题