2016-09-15 103 views
0

我是新來的數據結構,並開始與鏈接列表,我試圖在鏈表添加元素,但得到錯誤分段錯誤。 我正在用C語言實現它。錯誤:分段錯誤(代碼轉儲)

我不明白這是什麼錯誤意味着

CODE:

struct node 
{ 
int data; 
struct node *next; 
}; 
struct node *head; 
void fnInsert(int x){ 
    if(head==NULL){ 
    printf("head is null"); 
    node* temp=(node*)malloc(sizeof(struct node)); 
    temp->data=x; 
    temp->next=head; 
    head=temp; 
    } 
    else{ 
     node* temp=head; 
     struct node* previousNode; 
     do{ 
      temp=temp->next; 
      previousNode=temp; 
     }while(temp!=NULL); 
     node* temp1=(node*)malloc(sizeof(struct node)); 
      temp1->data=x; 
      previousNode->next=temp1; 
      temp1->next=NULL; 
    } 
}; 
void fnPrint(){ 
    struct node* temp=head; 
    printf("list is:\n"); 
    while(temp!=NULL){ 
     printf("%d",temp->data); 
     temp=temp->next; 
     printf("\n"); 
    } 
} 
int main(){ 
    head=NULL; 
    printf("how many numbers\n"); 
    int n,i,x; 
    scanf("%d",&n); 
    for(i=0;i<n;i++){ 
     printf("Enter the number\n"); 
     scanf("%d",&x); 
     fnInsert(x); 
     fnPrint(); 
    } 
} 

任何幫助,將不勝感激。

+0

分段錯誤意味着代碼訪問無效內存。使用調試器來幫助您找到問題。 – kaylum

+0

@kaylum 我在網上做這個,所以沒有選項可以調試:( –

+0

你有家用電腦嗎?很多調試工具都可以免費下載。 – kaylum

回答

5

的錯誤是在這些行:

temp=temp->next; 
previousNode=temp; 

它應該是相反的,即

previousNode=temp; 
temp=temp->next; 

在你的情況previousNode最終成爲NULL和您試圖訪問previousNode->next即提領一NULL指針。所以這是一個分段錯誤。

你在很多地方也使用過node*。您應該用struct node*替換它們全部或者您可以typedef