c - 分段故障链表

标签 c list linked-list segmentation-fault

在尝试创建一个简单的链表时,我一直遇到段错误。这个问题似乎出现在 print_list 函数内部。我已经尝试修复这个问题大约一个小时,但它仍然无法正常工作。我真的感谢您的帮助。这是代码:

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

struct node{
   double value;
   struct node *next;
   };
 struct node* getnode()
   {  
      struct node* create;
      create=(struct node*)malloc(sizeof(struct node));
      create->next=NULL;
      return create;
   }     


 void insert_at_beg(struct node*first,double x)
  {                                                     
      struct node*temp=getnode();
      if(!first)
      {
         temp->value=x;
         first=temp;
      }
      else
      { 
          temp->value=x;
          temp->next=first;
          first=temp;
      }
  }   
 void print_list(struct node*first)
  {    
       struct node*temp;
       temp=first;

       if(temp==NULL)
        { printf("The list is empty!\n");
          return;
          }

      while(temp!=NULL)
            if(temp->next ==NULL) // this is where i get the segmentation fault
            {  printf("%lf ",temp->value);
               break;
            }
            else
             { 
                printf("%lf ",temp->value);
                temp=temp->next;
             }

       printf("\n");
   }


   int main()
   {
       struct node *first;
       insert_at_beg(first,10.2);
       insert_at_beg(first,17.8);
       print_list(first);

       system("PAUSE");
   }

最佳答案

让它返回列表的新头部:

void insert_at_beg(struct node *first, double x)
{                                                     
      struct node *temp = getnode();
      temp->value = x;
      temp->next = first;
      return temp;
}

也比较简单。 :)

然后在 main() 中,执行:

   struct node *first = insert_at_beg(NULL, 10.2);
   first = insert_at_beg(first, 17.8);

关于c - 分段故障链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830117/

相关文章:

c++ - 从 vi "like running cpp program without exiting vi."运行各种 c 或 cpp 开发任务

c - MSVC 内联 ASM 到 GCC

python - 找到两个列表相同的基于 1 的位置

list - 列出文件夹但排除特定文件夹的批处理脚本

c++ - 将 C++ vector 转换为 C

c - Arduino 在 Sparkfun 2x16 LCD 上滚动

c++ - CUDA tex1Dfetch() 错误行为

java - 删除 ArrayList 中具有多个参数的元素

c++ - 在 C++ 中使用查找函数时遇到问题

c - 带有不需要的零的链表