我想读取PPM图像的字节,并将其存储在我的灵活成员数组中,该数组包含在一个结构中。我希望我没有搞砸拨款什么的。这就是它现在的样子:

typedef struct ppm {
    unsigned xsize;
    unsigned ysize;
    char data[];
} PPMImage;

int main(void)
{
    int c = 0;
    unsigned int rgb = 0;
    char arr[2];
    FILE *handle;
    PPMImage img;

    if((handle = fopen(filename, "rb")) == NULL)
        return 1;

    fscanf(handle, "%c%c", &arr[0], &arr[1]); // scanning width and height

    if(arr[0] != 'P' || arr[1] != '6')
        // error handling...

    c = getc(handle);
    while(c == '#') // getting rid of comments
    {
            while(getc(handle) != '\n');
            c = getc(handle);
    }
    ungetc(c, handle);
    if(fscanf(handle, "%u %u", &img.xsize, &img.ysize) != 2)
        // error handling...

    if(fscanf(handle, "%u", &rgb) != 1)
        // error handling...

    PPMImage *data = (PPMImage *)malloc(RANGE);

    if(fread(data, 3 * img.xsize, img.ysize, handle) != img.ysize)
        // error handling...

    for(int i = 0; i < RANGE; i++)
        printf("%c\n", data[i]); // ERROR POINT

    return 0;
}

我想我不知道数据会被保存在哪里,或者fread的参数是否正确。。有什么想法吗?这是输出:
warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘PPMImage’ [-Wformat]

最佳答案

因此,PPMImage *data = (PPMImage *)malloc(RANGE);创建一个新的局部变量,类型为PPMImage(一个结构!)而不是访问我认为您想要的img.data。。。
编辑以回答评论中的问题
修改struct ppm以使指针指向字符:

typedef struct ppm {
    unsigned xsize;
    unsigned ysize;
    char* data;
} PPMImage;

然后(假设有一个带R,G,B的字节矩阵):
img.data = malloc(3 * img.xsize * img.ysize);

// do error checking ...

然后
fread(img.data, 3 * img.xsize, img.ysize, handle)

// do error checking ...

09-26 03:44