I would like to read through the bytes of a ppm image and store it in my flexible member array, which is contained in a structure. I hope I didn't mess up the allocation or something. This is how it looks now:
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;
}
I guess I can't figure out where the data will be saved or if the arguments of fread are right.. any ideas? This is the output:
warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘PPMImage’ [-Wformat]
so, PPMImage *data = (PPMImage *)malloc(RANGE);
creates a new local variable, of type PPMImage
(a structure!) and is not accessing the img.data
which I think you want ...
Edit to answer the question in the comment
modify struct ppm
to have a pointer to a char:
typedef struct ppm {
unsigned xsize;
unsigned ysize;
char* data;
} PPMImage;
and then (assuming there is a byte matrix with R,G,B):
img.data = malloc(3 * img.xsize * img.ysize);
// do error checking ...
and then
fread(img.data, 3 * img.xsize, img.ysize, handle)
// do error checking ...