月孤影光 2021-08-17 17:49 采纳率: 100%
浏览 50
已结题

对链表进行操作时的一个段错误


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

struct test{
        int data;
        struct test* next;
};

void add(struct test* L1,struct test* new,int num)
{
        int i = 1;
        while( num>0 ){
                L1->data = i;
                new = (struct test*)malloc(sizeof(struct test));
                L1->next = new;
                new->next = NULL;
                L1 = new;
                num--;
                i++;
        }
}

void printfList(struct test* head)
{
        struct test* L;
        L = head;
        while(L->next!=NULL){
                printf("%d\n",L->data);
                L = L->next;
        }
}

int main(int argc,char** argv)
{
        if(argc!=2){
                perror("prgream is no good\n");
                exit(-1);
        }
        struct test* head;
        struct test* new;

        //creat head
        printf("1\n");
        head->data = 1;
        printf("2\n");
        head->next = NULL;
        printf("3\n");

        //cha ru other jie dian
        add( head,new,atoi( argv[1]) );

        //output all L1's data
        //printfList(head);
        //printf("-------------------------------\n");
        //printfList(head);

        return 0;
}

我把add( head,new,atoi( argv[1]) );这句话注释掉,就会报段错误;
加上这句话就可以正常运行;
这是为什么呀?
如果不加这句话:printf("1\n");顺利执行,printf("2\n");和printf("3\n");在终端上出不来

  • 写回答

1条回答 默认 最新

  • 快乐鹦鹉 2021-08-17 17:56
    关注

    代码有问题啊,head是个指针,你还没有分配空间,就进行head->data=1的操作,必死无疑,2和3不能输出肯定的了

    增加head = (struct test*)malloc(sizeof(struct test));
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月25日
  • 已采纳回答 8月17日
  • 创建了问题 8月17日

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算