2016-12-26 122 views
-1

我想建立一個鏈表,但由於某種原因我的頭沒有正確更新。下面是我的代碼,我打算不能工作的片段:設置指向結構的指針等於指向函數返回的結構的另一個指針?

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

node create_node(int data) { 
    node to_return = calloc(1, sizeof(struct node)); 
    to_return->data = data; 
    to_return->next = NULL; 
    return to_return; 
} 

int insert(int data, node head) { 
    if (head == NULL) { 
    head = create_node(data); 
    } 
    . 
    . 
    . 
    } 
    return 1; 
} 

int main(int argc, char **argv) { 

    node head = NULL; 
    insert(1, head); 

    printf("head->data: %d", head->data); 
} 

在這個例子中,我試圖創建鏈接列表的使用insert()的第一個節點。但是,我收到SEG錯誤,這意味着create_node()返回的to_return節點指針沒有正確設置到insert()中的節點頭部。我在這裏錯過了什麼?

編輯:我重複檢查和頭正在插入()正確設置。由於某些原因,更改不會持續

+0

我很抱歉,但我仍然困惑。我試圖在insert()中打印head-> data,並且我得到正確的值,但是由於某些原因,當程序退出函數insert() – YSA

+0

時,更改不會持久。還忘記提及該節點是指向一個結構。 – YSA

+1

**從來沒有**''typedef'指針! – Olaf

回答

3

一個指針傳遞給該節點:

int insert(int data, node* head) { 
    if (*head == NULL) { 
    *head = create_node(data); 
    } 
    . 
    . 
    . 
    } 
    return 1; 
} 

int main(int argc, char **argv) { 

    node head = NULL; 
    insert(1, &head); 

    printf("head->data: %d", head->data); 
} 

(和BTW說typedef會是讓人有些困惑,因爲插入函數的第二個參數實際上是struct node **型)

2

在C和C++中,除非明確標記爲引用,否則所有函數參數均按值傳遞。這包括指針參數。

您的insert函數試圖更改第一個參數,如果它是空指針的情況。這將不起作用,因爲對指針所做的任何更改都不會從該函數傳遞。如果您想要更改head,則需要將node *headnode& head(使用C++)傳遞給您的insert函數。