月孤影光 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日

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形