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

标签 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]

最佳答案

因此,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 ...

关于c - 将 PPM 的字节读入结构中的灵活成员数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22630956/

相关文章:

C++ 读入函数内部的结构数组?

c - 如何在运行时使用 POSIX clock() 函数监视 CPU 利用率?

c - 小 C 程序产生 500 多个 malloc?

c - 排序字符串数组

javascript - 使用 JavaScript 对逗号分隔的字符串数组进行排序

在 C 中按值将一维数组的内容复制到另一个

python - 在 Cython 中返回一个结构数组

visual-studio - Visual Studio 警告 C4133

c++ - Arduino 崩溃并在 "random points"处重新启动

C++ 在 LD_LIBRARY_PATH 上查找文件