c++ - gcc 中的指针导致段错误

标签 c++ linux gcc

我正在尝试使用以下代码实现一个链表,我遇到了段错误错误,请告诉我问题出在哪里。

我正在使用 ubuntu gcc 编译器,请给我一些建议

#include<iostream>

using  std::cout;
using  std::cin;


class ll
{
    struct node
    {
        int info;
        node *nextnode ;
    }*n;



public:
    ll()
    {
        n=NULL;
    }

    void getinfo()
    { 
        node *temp,*r;


        if( n==NULL )
        {
            temp=new node;
            cout<<" \n enter the first elements of linklist \n";
            int z;
            cin>>z;
            //i guess problem starts here
            temp->info=z;
            cout<<"the value of info is";
            temp->nextnode = NULL;
            n=temp;
        }
        else{
            temp=n;
            cout<<"heheh balls";
            while(temp->nextnode==NULL)
            {
                temp=temp->nextnode;
            }
            r=new node;
            cout<<"enter the element \t";
            int y;
            cin>>y; 
            r->info=y;
            r->nextnode=NULL;
            temp=r;
        }
    }

    void display()
    {
        node *temp=n;
        while(temp->nextnode==NULL)
        {
            cout<<temp->info;

        }
    }

};

int main()
{
    ll p;
    int v;
    cout<<"enter the number of elements to be added to linklist \t";
    cin>>v;
    //tryn to input linklist from terminal
    for(int i=0;i<v;i++)
    {
        p.getinfo();
    }
    p.display();

    return 0;
}

最佳答案

while(temp->nextnode==NULL)
{
    temp=temp->nextnode;
}
....
temp=r;

应该是

while(temp->nextnode!=NULL)
{
    temp=temp->nextnode;
}
....
temp->nextnode=r;

同样适用:

void display()
{
    node *temp=n;
    while(temp->nextnode==NULL)
    {
        cout<<temp->info;

    }
}

应该是:

void display()
{
    node *temp=n;
    while(temp!=NULL)
    {
        cout<<temp->info;
        temp = temp->nextnode;
    }
}

关于c++ - gcc 中的指针导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100228/

相关文章:

c++ - 指向错误 : Linking Error in C++ 的指针

linux - 如何使用 Bash 从文件运行命令?

C++/Linux : how do you write a thread-safe library that uses sockets?

c - 为什么 scanf 或 fgetc 不能按预期工作

linux - 制作[1] : arm-linux-gcc: Command not found in ubuntu

c++ - 模板问题: Can compiler deduce template type in static method

c++ - C++ 跨平台应用程序中本地化文本的最佳实践?

linux - parent 和 child 之间的沟通

创建我自己的进程名称并在 Top Linux 中显示

c++ - 删除导致段错误的 cout 语句