2014-11-06 168 views
0

我嘗試用插入函數在雙鏈表的末尾插入節點,但在第二次插入後,進程執行突然停止。我試着檢查插入函數中使用的所有指針變量的地址,他們表明我的代碼工作正常,直到第三次插入函數。我如何修復我的代碼?在雙向鏈表的末尾插入一個節點

#include <stdio.h> 
#include <stdlib.h> 

struct node { 
    int data; 
    struct node* next; 
    struct node* prev; 
}; 

void insert(struct node** header,int data) { 
    struct node* newnode=(struct node*)malloc(sizeof(struct node*)); 
    newnode->data=data; 
    newnode->prev=NULL; 
    newnode->next=NULL; 

    if(*header == NULL) { 
     *header=newnode; 
     return; 
    } 

    struct node* temp = *header; 

    while(temp->next != NULL) { 
     temp=temp->next; 
    } 

    temp->next = newnode; 
    newnode->prev = temp; 
    printf("%d\n**\n", temp->next); 
} 

void main() { 
    struct node* head = NULL; 
    insert(&head, 4); 
    insert(&head, 45); 
    printf("\n main head %d", head); 
    insert(&head, 8); 
    printf("testing"); 
    insert(&head, 69); 
} 
+0

關於架構的建議:讓'insert'帶一個'struct node *'並返回'struct node *';我發現這有點容易理解,因爲你不必用雙指針搞亂。 – APerson 2014-11-06 14:06:21

+1

您應該使用'%p'格式來打印指針或保留'%d'格式並打印節點數據。 – 2014-11-06 14:09:22

+2

@APerson:或者可能創建一個保持頭部和尾部的列表結構,並使函數在指向該結構的指針上工作。 (返回新的頭總是會產生一個冗餘 - 「head = something(head)」 - 我發現比傳遞雙指針更醜陋。) – 2014-11-06 14:13:40

回答

1

您還沒有分配足夠的內存

struct node* newnode=(struct node*)malloc(sizeof(struct node*)); 
// here you allocate only 4 bytes (or 8 bytes on a 64 bit system) 

應該是:

struct node* newnode = (struct node*)malloc(sizeof(struct node)); 

然後一切工作正常。

+2

或'sizeof * newnode',毫無疑問,即將分配的內容與指定的指針類型。 [並在'malloc()']上丟失了這個強制類型(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – WhozCraig 2014-11-06 14:11:01