2015-05-14 77 views
0

我做了更改,但 我不能添加超過2個節點它將freez,但如果1或2節點將工作良好,原因是什麼?我gave_up 我也沒有辦法爲 這是我的代碼,直到時間無法添加節點到鏈接列表

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 

struct info{ 
    int num; 
    char name[15]; 
    struct info *next; 
}; 

struct info *first,*current,*new_s; 
int struct_num; 
void add_struct(void); 

int main(){ 
    first=NULL; 
    add_struct(); 
    puts("done"); 
    add_struct(); 
    puts("done"); 
    add_struct(); 
    puts("done"); 

    return(0); 
} 

//結構添加功能

void add_struct(void){ 

new_s= malloc (sizeof(struct info)); 
if(!new_s){ 
    puts("error"); 
    exit (1); 
} 
if(first==NULL){ 
    first = current= new_s; 
    first->next = NULL; 
}else{ 
    current=first; 

    while(current->next!=NULL){ 
     current=current->next; 
    } 

    current->next=new_s; 
    current=new_s; 
} 

struct_num++; 
} 
+2

標準警告:請[不要投(http://stackoverflow.com/q/605845/2173917)的malloc'的返回值() ''和'C'中的家庭。 –

+0

使用[sentry節點](http:// pastebin。com/JAfq6ep1)可以幫助您避免所有特殊情況,例如空列表,第一個節點,最後一個節點等 – sp2danny

回答

5

在你的代碼的問題是

if(first==NULL){ 
first->next=new_s; 

如果first是NULL,你應該而不是 dererefence它。這在邏輯上是錯誤的,並調用undefined behaviour

我認爲,你想要什麼,而不是,有點像(僞代碼)

if(first == NULL){ 
    first = new_s; 
    first->next = NULL; 

這就是說,

current->next=new_s; 
    current=new_s; 

看起來也有問題。第二條語句有錯,而不是必需的,相反,你可以添加類似

current->next = new_s; 
    current->next->next = NULL; 

最後,您struct_num變量應該是全球,按照目前的使用情況。

注:

  1. main()推薦的簽名是int main(void)
  2. do not cast返回值malloc()和家庭C
  3. 在使用返回的指針之前,請始終檢查malloc()是否成功。
+0

非常感謝您 – technomacx

+0

@technomacx不客氣。 :-)順便說一句,你可以考慮[接受](http://meta.stackexchange.com/q/5234)幫助你的答案。 –

+0

我做了更改,但當我嘗試從3個節點或更多的其freez,2節點工作良好的列表,是什麼原因? – technomacx

0

功能add_struct是錯誤的 例如,如果第一等於零,那麼你可以不寫

first->next=new_s; 

考慮到是沒有任何意義的聲明函數struct_num,因爲它的局部變量在退出函數後總是被銷燬,而且它在函數中甚至沒有被初始化。

int struct_num; 

如果您需要列表中的節點數量,請將它放在函數之外。

函數本身可以看看下面的方式

int struct_num; 

int add_struct(void) 
{ 
    new_s = (struct info *)malloc(sizeof(struct info)); 

    if (new_s == NULL) return 0; 

    // initialize data members num and name of the allocated structure 
    new_s->next = NULL; 

    if (first == NULL) 
    { 
     first = new_s; 
    } 
    else 
    { 
     current->next = new_s ; 
    } 

    current = new_s; 
    ++struct_num; 

    return 1; 
}