由于gcc中的指针导致的分段错误

Segmentation fault due to pointer in gcc

本文关键字:分段 错误 指针 gcc 由于      更新时间:2023-10-16

我正试图使用以下代码实现链表,我得到了段故障错误,请告诉我问题在哪里。

我正在使用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;
    }
}

代码中有几个错误,如下所示:

 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->nextnode  = r;
      }
  }
下功能:

  void
  display ()
  {
    node *temp = n;

下一行改变了,当你有一个节点

时继续打印数字
while (temp)
  {
    cout << temp->info;

不要忘记移动到下一个节点

        temp = temp->nextnode;
      }
  }

就是这样,它成功了