使用节点结构的分段错误

时间:2017-10-17 22:30:44

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

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

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;}}

1 个答案:

答案 0 :(得分: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;
}`