2016-01-20 104 views
0

所以我最近拿起了C,並且我正在按照一個簡單的在線教程創建和打印鏈表。我已經跟着它一步一步,出於某種原因,教程中的人能夠列出他的列表,而我不是。這讓我瘋狂。當我構建並運行(使用CodeBlocks)時,什麼都沒有顯示出來。使用CodeBlocks以C打印鏈表

他正在使用一些其他的文本編輯器,也許是一個不同的編譯器,但我不能爲我的生活看到完全相同的代碼可以有兩種不同的行爲?任何人有任何想法?代碼如下:

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

struct List { 
    struct Node *head; 
}; 

void pushList(struct List *linkedList, int value) { 
    if (linkedList->head == NULL) { 
     struct Node *newNode; 
     newNode = malloc(sizeof(struct Node)); 
     newNode->data = value; 
     linkedList->head = newNode; 
    } else { 
     struct Node *tNode = linkedList->head; 
     while (tNode->next != NULL) { 
      tNode = tNode->next; 
     } 
     struct Node *newNode; 
     newNode = malloc(sizeof(struct Node)); 
     newNode->data = value; 
     tNode->next = newNode; 
    } 
} 

void printList(struct List *linkedList) { 
    struct Node *tNode = linkedList->head; 
    while (tNode != NULL) { 
     printf("This node has a value of %d\n", tNode->data); 
     tNode = tNode->next; 
    } 
} 

int main() { 
    struct List newList = { 0 }; //This initializes to null 

    pushList(&newList, 200); 
    pushList(&newList, 300); 
    pushList(&newList, 400); 
    pushList(&newList, 500); 

    printList(&newList); 
    return 0; 
} 
+0

適合我。你是否包含''stdio.h'和'stdlib.h'? –

+0

'newNode-> data = value;' - >'newNode-> data = value; newNode-> next = NULL;' – BLUEPIXY

回答

1

您忘記初始化newNode->next = NULL;malloc不會初始化它返回給您的內存塊,您對此負責。

如果內存指向newNode發生是所有零,你的代碼可能會奏效,如果不是,它可能會崩潰,它被稱爲未定義行爲,不同的環境會表現不同,這解釋了爲什麼男人在教程和PaulRooney得到預期的行爲,你不這樣做。

+0

是的。完善。謝謝。來自Java,我假設C只是初始化爲null,如果他們從來沒有被手動初始化。我猜不會。頭部劃傷的事情是沒有任何錯誤或任何東西。它編譯得很好。只是沒有出現。這是正常的嗎? –

+0

當被告知需要使用諸如'-Wall -Wextra -Werror'之類的適當選項來發布有用診斷信息的現代編譯器時,但對於這種特殊情況,這是一個經典的錯誤,我認爲任何編譯器都不會有所幫助。這太糟糕了,但現在你知道你必須非常小心'malloc'。 – chqrlie