【问题标题】:Segmentation Fault in using a node struct使用节点结构时的分段错误
【发布时间】:2018-03-29 17:43:53
【问题描述】:

我有这种方法给我一个分段错误,我无法弄清楚。我们必须删除与给定名称匹配的节点。

typedef struct node
{
int id;
char* name;
struct node* next;
} node;

node* rem_inorder(node** head, char* key_name)
{

node* temp = *head;
int found =0;
while(temp -> next != NULL &&!found)
{

if(temp -> name == key_name){
    printf("works");
    found = -1;}
else {
    temp = temp ->next;}}
if(found == -1)
{return temp;} 
else
{return NULL;}}

【问题讨论】:

  • 我在显示的代码中没有看到任何问题。在您使用此功能之前,您的链接列表可能已从其他地方损坏。您所做的唯一取消引用是temp->,这表明*head 不好。
  • *head 不好是什么意思。这只是一个遍历列表的临时变量。我应该如何将它分配给头部?
  • 我是说*head 可能是NULL 或一些垃圾值,如果您确实在此函数中遇到了段错误。
  • 使用调试器查找发生段错误的行。如果您无法解决问题,请发帖Minimal, Complete, and Verifiable example

标签: c list segmentation-fault singly-linked-list


【解决方案1】:

对于初学者,该函数具有未定义的行为,因为对于空列表,表达式 *head 的值可以等于 NULL。在这种情况下,此表达式 temp -> next 将无效。

在搜索节点时,您还必须比较字符串而不是指针。

根据分配的描述,您必须从列表中删除找到的节点。

函数可以通过以下方式定义

node * rem_inorder( node **head, const char *key_name )
{
    node *target = NULL;

    while ( *head && strcmp( ( *head )->name, key_name ) != 0 )
    {
        head = &( *head )->next;
    }

    if ( *head != NULL )
    {
        target = `*head;
        *head = ( *head )->next;
        target->next = NULL;
    }

    return target;
}`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2021-02-07
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多