我想通读 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/