2017-10-17 75 views
0

我有這種方法給我一個分段錯誤,我無法弄清楚。我們必須刪除與給定名稱相匹配的節點。使用節點的分段錯誤struct

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

沒有問題我中所示的代碼看到。在你開始使用這個功能之前,你的鏈表可能會從其他地方斷開。你做的唯一的解除引用是'temp->',這表明'* head'不好。 – yano

+0

你的意思是說這個*頭是不好的。這只是通過列表的一個臨時變量。我還應該如何將它分配給頭部? –

+0

我在說'* head'可能是'NULL'或者一些垃圾值,如果你確實在這個函數中出現了段錯誤。 – yano

回答

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; 
}` 
+0

非常感謝! –