【问题标题】:LEETCODE #148 Sort List , runtime error: member access within null pointer of type 'struct ListNode'LEETCODE #148 排序列表,运行时错误:成员访问类型为\'struct ListNode\'的空指针
【发布时间】:2022-12-19 00:42:23
【问题描述】:
struct ListNode* sortList(struct ListNode* head){

    struct ListNode *temp, *change;
    int temp_data;
    temp = head;
    change = head->next;  //<<<<<<<<<<<<<<<<<<

    while(temp)
    {
        change = temp->next;
        while(change)
        {
            if (temp->val > change->val)
            {
                temp_data = temp->val;
                temp->val = change->val;
                change->val = temp_data;
            }

            change = change->next;
        }



        temp = temp->next;
    }

    return head;
}

leetcode Link Given the head of a linked list, return the list after sorting it in ascending order.

我试图在 Dev c++ 中编写相同的代码,一切似乎都正常。 在 about 的代码中,我试图将指针更改为指向 head 中的下一个节点,leetcode 给了我一个错误:

Line 13: Char 12: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]

是什么导致了这个错误?它不应该是错误的吧?

【问题讨论】:

  • 可能必须处理的一种情况是空列表。在这种情况下,传递给函数的 head 指针将为空。如果您描述的错误是由您标记的行触发的,那么这就是原因。
  • 在这种情况下,程序是错误的,无论它是否崩溃或报告诊断。此外,看起来您可以简单地完全删除该行,因为该函数从不读取它写入change 的值。后来的change = temp-&gt;nextchange被读取之前执行。
  • 你应该edit并显示minimal reproducible example。那么我们可以给你一个更准确的答案。

标签: c sorting linked-list


【解决方案1】:

该错误是由于当您尝试在第 13 行访问它的 val 成员时 change 指向一个空指针。发生这种情况是因为 temp-&gt;next 为空,这意味着 temp 指向最后一个节点链表。

要解决此问题,您需要在尝试访问其成员之前检查temp-&gt;next 是否为空。

【讨论】:

  • 这是一个主要基于猜测的糟糕解释。
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多