2015-05-18 65 views
0

我遇到分段錯誤,我不知道問題出在哪裏。鏈接列表分段故障

#include "stdio.h" 
#include "stdlib.h" 

struct node { 
    int data; 
    struct node *next; 
    }; 
    struct node *head = NULL; 
    struct node * curr; 
    struct node * newNode; 

void createList(){ 

    int data,n , i ; 
    scanf("%d",&n); 
    for (i = 0 ; i < n ;i++){ 
     scanf("%d",&data); 
     curr = head; 
     newNode = (struct node*)malloc(sizeof(struct node)); 
     newNode->data=data; 
     newNode->next=NULL; 
     if (curr == NULL){ 
      head = newNode; 
     }else 
      while (curr->next != NULL){ 
       curr = curr->next; 
      } 
      curr->next = newNode; 
    } 

} 

int main(int argc, char const *argv[]) 
{ 

    createList(); 
    return 0; 
} 

請問你能弄清楚哪裏? 第一次迭代很好,但當i = 1時,出現錯誤。

+2

調試器在哪裏指出問題? – jxh

+1

[不要強制轉換'malloc()']的返回值(http://stackoverflow.com/a/605858/1983495)。 –

回答

5

對齊是不足以使一個代碼用C ;-)

需要大括號。沒有它,curr->next = newNode;聲明在else塊之外,這不是你想要的。

if (curr == NULL){ 
       head = newNode; 
    } 
    else { 
       while (curr->next != NULL){ 
        curr = curr->next; 
       } 
       curr->next = newNode; 
    } 
+0

作品很好,謝謝,我沒有注意到 –