liunx_hello 2019-02-18 13:51 采纳率: 100%
浏览 839
已采纳

新建单链表,运行时出现段错误,怎么改呀?

建立一个单链表函数,在编译的时候没有错误,在运行的时候出现 段错误
在linux环境下编译的,想知道是哪里出错了呀?

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

/*定义链表结构内容*/
struct list
{
        char name[10];
        long int number;
        struct list *next;

};

/*创建链表插入函数,*/
void insert(struct list *head)
{
        int n=1;
        struct list *p1,*p2;


        p1->next = NULL;
        p1=p2=(struct list*)malloc(sizeof(struct list));
        printf("please input the %d th name :  number  : \n",n++);
        scanf("%s%ld",p1->name,&p1->number);
        /*p1指向新分配的malloc()起始地址,若新分配的p1里面有内容,p2=p1,继续新建结点;若没有=内容则结束新建结点*/
                while((p1->number)>0)
        {
                if(head ==NULL) head = p2;
                else p2->next=p1;
                p2= p1;
                p1=(struct list*)malloc(sizeof(struct list));
                printf("please input the %dth name :  number  : \n",n++);
                scanf("%s%ld",p1->name,&p1->number);
                p1->next = NULL;
        }
        free(p1);      /*释放没有内容的新结点*/
}

/*輸出链表中的内容*/
void putout(struct list *head)
{
        while(head!=NULL)
        {
                printf("name:%s\t number:%ld\n",head->name,head->number);
                head = head->next;
        }

}

int main()
{
        struct list *head;
        head=NULL;
        insert(head);
        putout(head);
        return 0;
}                                                                                                                                                                                         
  • 写回答

1条回答 默认 最新

  • 45度凝视 2019-02-18 14:07
    关注

    定义了struct list *p1,*p2;两个指针之后,未进行初始化,而直接调用p1->next = NULL;是错误的。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示