【问题标题】:C++ Struct Pointer SegfaultC++ 结构指针段错误
【发布时间】:2013-11-10 02:04:37
【问题描述】:

首先,提前感谢所有回复此帖子的人。

其次,我浏览了所有其他帖子,但找不到任何对我有帮助的内容(抱歉,我是 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(指向链表中的下一项)和data(节点的数据)。

有什么想法吗?

linux用户

编辑:问题已解决 - 非常感谢所有离开 cmets 的人!

遗憾的是,我无法使用 **pHead 取消引用解决方案,因为问题出在自动输入函数参数的网站上。然而,使用下面的 cmets,我制作了一个简单的程序,希望能为像我这样的其他初级 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;  
}

问候,

linux用户

【问题讨论】:

  • 另外,当我尝试head -&gt; data 时,我收到了一个段错误。
  • 您确定Nodes 总是将其下一个值初始化为NULL?也许向我们展示您如何初始化您操作的列表(即什么是头?)。此外,这看起来像 append(),而不是 insert()
  • 并非没有更多上下文。这叫什么?你确定调用者传入的是非空的head
  • 一开始,如果head 为NULL,那你就麻烦了。我建议函数的第一行应该是cout &lt;&lt; head &lt;&lt; endl; cout &lt;&lt; head -&gt; data &lt;&lt; endl;
  • 感谢大家的快速响应——这是一个基本的 HackerRank 问题,它为您提供了一个链表,保证 *next 将始终指向另一个节点或 NULL。此外,它应该是 append(),但被命名为(默认情况下)插入 - 感谢您指出这一点。

标签: c++ pointers struct


【解决方案1】:

这里最可能的问题是您不能使用Insert 来“启动”您的列表:如果headNULL 开始,则循环将立即失败。此外,在第一次插入时,您将无法分配 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;
}

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多