c - 获取段错误

标签 c segmentation-fault

为机器问题编写一些代码;我们刚刚开始使用指针等,所以我不太确定哪里错了。运行调试显示它是行: for(i=0; i<*y;i++) 抛出错误,尽管我确定 for(j=0;j<*x ;j++) 空间。任何帮助将不胜感激。

    int readImage(char* fileName,
                  int image[MAX_IMAGE_SIZE][MAX_IMAGE_SIZE][NUM_CHANNELS],
                  int* x,
                  int* y,
                  int* max)
    {
        /* Variable declarations*/
        int i=0; 
        int j=0;
        int k=0;
        int num=0;
        char c;
        /* Opens file, skips first line*/
        FILE *input=fopen(fileName, "r");
        if(!input)
            return -1;
        do
            c=getc(input);
        while(c!='\n');
        /*Saves the x and y components into a variable */
        fscanf(input,"%d",&x);
        fscanf(input,"%d",&y);
        fscanf(input,"%d",&max);
        /*Cycles through file, reading it into the array */
        for(i=0; i<*y;i++)
        {
            for(j=0;j<*x;j++)
            {
                for(k=0;k<NUM_CHANNELS; k++)
                {
                    /*Takes input */
                    fscanf(input, "%d",&num);
                    /*Stores into the array in the form of array[x][y][color] */
                    image[j][i][k]=num;
                }
            }
        }
        /*Closes input  */
        fclose(input);
        return 0;
    }

最佳答案

变量 x、y 和 max 已经是指针。所以你不需要在 fscanf() 中使用地址 &。此外,如果调用者没有,则需要为它们分配内存。

只需使用:

  fscanf(input,"%d",x);
  fscanf(input,"%d",y);
  fscanf(input,"%d",max);

并确保调用者为它们分配了内存。否则,使用 malloc()

关于c - 获取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10003917/

相关文章:

c - 如何减少下面代码执行的时间?

c++ - vector vector 的段错误

c++ - Lambda 返回引用会导致段错误 - 为什么?

c - C 中的段错误(初学者)

java - 如何检索 PostgreSQL 列名并导入到 Matlab 中的结构数据

c - Bison 中缀计算器的计算结果始终为 0

c - read() 的奇怪行为

c - 在 c 中使用数组查找数字中的重复数字 (C)

c - 循环获取主机、网络、协议(protocol)和服务数据库中的多个条目

c++ - 仅在多核上运行时出现段错误