Ошибка сегментации на fscanf - PullRequest
0 голосов
/ 05 марта 2020

Я пишу программу для хранения файлов PPM, и я застрял с передачей значений RGB. Первый fscanf в l oop вызывает ошибку сегментации и тестовую строку printf до того, как она не печатается. Я пытался использовать переменную "temp" в качестве int, и все еще была та же проблема.

(остальная часть программы не включена, так как она не имеет отношения к вопросу)

typedef struct{
    unsigned char r, g, b;
} pixel;

typedef struct{
    int width, height, max;
    pixel *rgbdata;
} PPM;

static PPM * getPPM(FILE * f) {

    printf("start getppm\n");

    char line[100];
    PPM *image;
    char temp[7];
    int rval, gval, bval;
    int counter;

    image = (PPM *)malloc(sizeof(PPM));
    printf("memory alloc\n");

    fgets(line, sizeof(line), f);
    if(line[0]!='P' || line[1]!='3'){
        fprintf(stderr, "File is not correct PPM format \n");
        exit(1);
    }
    printf("valid PPM file\n");

    do{
        fgets(line, sizeof(line), f);   
    }while(line[0]=='#');

    fscanf(f, "%d %d", &image->width, &image->height);
    fscanf(f, "%d", &image->max);

    image->rgbdata = (pixel*)malloc(image->width * image->height * sizeof(pixel));

    printf("pixel memory alloc\n");

    do{
        printf("started loop");
        fscanf(f, "%d", temp[0]);
        printf("%d \n", temp[0]);
        image->rgbdata[counter].r = temp[0];
        fscanf(f, "%d", temp[0]);
        image->rgbdata[counter].g = temp[0];
        fscanf(f, "%d", temp[0]);
        image->rgbdata[counter].b = temp[0];
    }while(1);  

...