【问题标题】:Reading bytes of PPM into a flexible member array in a struct将 PPM 的字节读入结构中的灵活成员数组
【发布时间】:2014-03-25 09:56:54
【问题描述】:

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

【问题讨论】:

标签: c arrays struct malloc ppm


【解决方案1】:

所以,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 ...

【讨论】:

  • 那么如果我想把它存储在img.data中,我该怎么做呢?
  • 我需要保留字符数据[];在结构中,我无法更改它(它已被分配)。有问题吗?
  • 另外,我该如何释放它? free(img.data)?
  • 你需要char*,你不能动态分配一个未知大小的数组。是的,只是免费的(img.data)
  • 那么灵活的数组成员此时无法使用?即使没有分配?我会用 char 试试看。
猜你喜欢
  • 2011-03-04
  • 2011-07-25
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 2012-09-22
相关资源
最近更新 更多