将PPM的字节读入结构中的灵活成员数组

时间:2014-03-25 09:56:55

标签: c arrays struct malloc ppm

我想读取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]

1 个答案:

答案 0 :(得分:2)

所以,PPMImage *data = (PPMImage *)malloc(RANGE);创建了一个新的局部变量,类型为PPMImage(一个结构!),并且没有访问我认为你想要的img.data ......

编辑以回答评论中的问题

修改struct ppm以获得指向char的指针:

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 ...