C++ 结构指针隔离错误

C++ Struct Pointer Segfault

本文关键字:错误 隔离 指针 结构 C++      更新时间:2023-10-16

首先,提前感谢所有回复这篇文章的人。

其次,我

浏览了所有其他帖子,找不到任何对我有帮助的东西(抱歉,我是C++新手)。

这是我的代码:

Node* Insert(Node *head,int data) //for linked lists
{
  Node* current = head;
  while(current -> next != NULL){
      current = current -> next;
  }
  cout << head -> data;
  Node *last = new Node();
  last -> data = data;
  last -> next = NULL;
  current -> next = last;
  return head;
}
似乎

(通过行注释的反复试验)当前指针中下一个属性的访问似乎是问题所在,但我似乎无法弄清楚原因。Node 结构有两个属性,*next(指向链表中的下一项)和数据(节点的数据)。

对正在发生的事情有什么想法吗?

Linuxuser

编辑:问题解决了 - 非常感谢所有发表评论的人!

可悲的是,我无法使用**pHead取消引用解决方案,因为问题出在自动输入函数参数的网站上。但是,使用下面的评论,我制作了一个简单的程序,我希望它能为像我这样的其他初级C++程序员详细介绍这个问题:

Node* Insert(Node *head,int data)
{
    if(head == NULL){
        Node* last = new Node();
        last -> data = data;
        return last;
    }
    Node *current = head;
    while(current -> next != NULL){
        current = current -> next;
    }
    Node *last = new Node();
    last -> data = data;
    last -> next = NULL;
    current -> next = last;
    return head;  
}

问候

Linuxuser

这里最可能的问题是你不能使用Insert来"快速启动"你的列表:如果head开始NULL,循环将立即失败。此外,在第一次插入时,您将无法分配head

若要解决此问题,请将第一个参数从 Node *head 更改为 Node **pHead ,传递指向头指针的指针,并向 Insert 函数的代码添加额外的取消引用级别:

Node* Insert(Node **pHead, int data)
{
    while(*pHead != NULL){
        pHead = &((*pHead)->next);
    }
    Node *last = new Node();
    last -> data = data;
    last -> next = NULL;
    *pHead = last;
    return last;
}

请注意,即使您将指针传递到设置为 NULL 的指针Node此方法也将起作用:

Node *head = NULL;
Insert(&head, 1);
Insert(&head, 2);
Insert(&head, 3);