函数/结构/指针中的分段错误

时间:2013-12-11 02:27:33

标签: c function pointers file-io struct

我试图读取两个图像,然后将它们输出到两个多维数组中,然后在程序中翻转/混合/输出图像。有没有人有任何想法,为什么我继续得到分段错误?我知道它在ReadImages调用内,因为它符合它,然后当我执行它时 - 第一个调用出现,但在那之后失败....

void ReadImages(struct ImageType *imgur, struct ImageType *imgur2)
{
    int i = 0, j = 0;
    char filename[30];
    char filename2[30];

    //Scanning in the first file.
    FILE *inputfile;
    fprintf(stdout, "Please enter the filename/location of the first image\n");
    fscanf(stdin, "%c", &filename);
    inputfile = fopen(filename, "r");
    if(inputfile = NULL)
    {
        fprintf(stderr,"Sorry you didn't specify correctly\n");
    }

    fscanf(inputfile,"%[^\n]%c", imgur->ppImage, &imgur->newlinechar);
    fscanf(inputfile,"%[^\n]%c", imgur->comment, &imgur->newlinechar);
    fscanf(inputfile,"%i %i", &imgur->width, &imgur->height);
    fscanf(inputfile,"%i", &imgur->maxColor);

    for(i = imgur->height - 1; i >= 0; i--)
    {
        for(j = 0; j > imgur->width; j++)
        {
            fscanf(inputfile,"%i", &imgur->image[i][j].red);
            fscanf(inputfile,"%i", &imgur->image[i][j].green);
            fscanf(inputfile,"%i", &imgur->image[i][j].blue);
        }
    }

    //Scanning in the second file.
    FILE *inputfile2;
    fprintf(stdout, "Please enter the filename/location of the second image\n");
    fscanf(stdin, "%c", filename2);
    inputfile2 = fopen(filename2, "r");
    if(inputfile2 = NULL)
    {
        fprintf(stdout,"Sorry you didn't specify the filename/location correctly\n");
    }

    fscanf(inputfile2, "%[^\n]%c", imgur2->ppImage, &imgur2->newlinechar);
    fscanf(inputfile2, "%[^\n]%c", imgur2->comment, &imgur2->newlinechar);
    fscanf(inputfile2, "%i %i", &imgur2->width, &imgur2->height);
    fscanf(inputfile2, "%i", &imgur2->maxColor);

    for(i = imgur2->height - 1; i >= 0; i--)
    {
        for(j = 0; j > imgur->width; j++)
        {
            fscanf(inputfile2,"%i", &imgur2->image[i][j].red);
            fscanf(inputfile2,"%i", &imgur2->image[i][j].green);
            fscanf(inputfile2,"%i", &imgur2->image[i][j].blue);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你有

fscanf(stdin, "%c", &filename);

读取文件名,但%c是单个字符的格式说明符。您希望%s代替字符串。 &前面的filename也是不必要的。

同样适用于:

fscanf(stdin, "%c", filename2);