无法将节点添加到链接列表

tec*_*acx 0 c linked-list

我做了更改,但我不能添加超过2个节点,它将freez但如果1或2节点将运行良好是什么原因??? 我给了我一无所知,这是我的代码,直到时间

#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);
}
Run Code Online (Sandbox Code Playgroud)

// struct add function

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++;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 5

代码中的问题是

if( first==NULL){
first->next=new_s;
Run Code Online (Sandbox Code Playgroud)

如果first是NULL,你应该 dererefence它.它在逻辑上是错误的,并调用未定义的行为.

我想,你想要的是(伪代码)

if(first == NULL){
    first = new_s;
    first->next = NULL;
Run Code Online (Sandbox Code Playgroud)

那说,

    current->next=new_s;
    current=new_s;
Run Code Online (Sandbox Code Playgroud)

也看起来有问题.第二个声明是错误的而不是必需的,相反,你可以添加类似的东西

   current->next = new_s;
   current->next->next = NULL;
Run Code Online (Sandbox Code Playgroud)

最后,根据当前用法,您的struct_num变量应该是全局变量.

注意:

  1. 推荐的签名main()int main(void).
  2. 不要投入malloc()和家人的返回值C.
  3. malloc()在使用返回的指针之前始终检查是否成功.