2015-05-14 46 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; 
}