2016-04-30 173 views
-1
#include<stdio.h> 
#include<stdlib.h> 

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

int main() 
{ 
    struct node* head = NULL; 
    struct node* second = NULL; 
    struct node* third = NULL; 

    head = (struct node*)malloc(sizeof(struct node)); 
    second = (struct node*)malloc(sizeof(struct node)); 
    third = (struct node*)malloc(sizeof(struct node)); 

    head->data = 1; //assign data in first node 
    head->next = second; // Link first node with the second node 

    second->data = 2; //assign data to second node 
    second->next = third; 

    third->data = 3; //assign data to third node 
    third->next = NULL; 

    return 0; 
} 

我是新手指針,我發現這個代碼在書中創建鏈表。我不明白爲什麼主函數中的前三行代碼是必需的。爲什麼我們要求指向節點的指針是空指針? 任何幫助將不勝感激,因爲這個概念對我來說似乎很難。創建三個節點的鏈表

+0

它只是指針變量的聲明,因爲許多編譯器會拋出一個錯誤爲未初始化的 – piyushj

+0

但是爲什麼NULL是特別的? – user34304

+2

沒有理由對它們進行初始化。在現代C中,甚至沒有必要將它們與'malloc'分開;你可以寫'struct * node head = malloc(sizeof(struct node));' 用'NULL'指針進行初始化並不是真正值得推薦的地方,它只是讓編譯器難以產生正確的診斷。例如。它不能抱怨未初始化的變量,因爲它們現在已經初始化了。 –

回答

1

您問爲什麼前三行是必要的,答案是:「他們不是」。沒有必要將它們全部設置爲NULL,但你需要來聲明它們。真的,你可以在第一部分冷凝爲:

struct node* head = (struct node*)malloc(sizeof(struct node)); 
struct node* second = (struct node*)malloc(sizeof(struct node)); 
struct node* third = (struct node*)malloc(sizeof(struct node)); 

主要理由將它們設置爲NULL(因爲你的代碼目前確實)是爲了保證「未定義行爲」不會被調用。

4

根本沒有理由初始化它們。我認爲這是一種反模式。在過時的ANSI C(這是在1999年棄用當C99出來),最好是不初始化他們都:

struct node* head; 
struct node* second; 
struct node* third; 

head = malloc(sizeof(struct node)); 
second = malloc(sizeof(struct node)); 
third = malloc(sizeof(struct node)); 

現在編譯可以農產品診斷,如果你忘了malloc內存second

struct node* head; 
struct node* second; 
/* ... */ 
head = malloc(sizeof(struct node)); 
/* ... */ 
do_something(head, second); 

將與-Wall原因gcc編譯抱怨:

% gcc -Wall test.c 
test.c: In function ‘main’: 
test.c:11:5: warning: ‘second’ is used uninitialized in this function [-Wuninitialized] 
    do_something(head, second); 
    ^

然而,有您初始化secondNULL有:

struct node* head = NULL; 
struct node* second = NULL; 
// ... 
head = malloc(sizeof(struct node)); 
// ... 
do_something(head, second); 

GCC將讓你的錯誤默默地傳遞:

% gcc -Wall test.c 
% 

在現代C(中也已經過時的C99,或者當前C11; ANSI C a.k.a C89已被棄用近二十年),甚至沒有必要將它們與malloc行分開;你可以寫

struct node* head = malloc(sizeof(struct node)); 
struct node* second = malloc(sizeof(struct node)); 
struct node* third = malloc(sizeof(struct node)); 

這樣好多了,因爲變量會立即用適當的值初始化。


至於與NULL,而不是未初始化值初始化 - 嗯,這隻能如果你使用指針值,而不提領它很重要。但是,解引用空指針或解引用未初始化值的指針會導致未定義行爲。他們都不需要崩潰。

+0

好吧,你現在可以有你的快艇,我去喝咖啡:) –