For my Project I need to read an PPM(P3) image into memory. Because I want to rotate the input picture and therefore I would like to go through an x and y axis/array.
First I read the values of the image into an "unsigned char" since the color values used are only between 0 and 255 and to save memory I convert them into unsigned chars.
Every pixel in the PPM image has a red, green, blue values.
For this, I created this typedef struct
.
typedef struct{
unsigned char red;
unsigned char greed;
unsigned char blue;
} color;
I tried to make a simple 2-dimensional array like this:
color inputColor[pictureHeight][pictureWidth];
But this fails very fast when the pictures get bigger. I am trying to make it work, so I can allocate that 2d array with malloc. One attempt was:
color *inputColor[pictureHeight][pictureWidth];
//Allocating memory
for (int y = 0; y < pictureHeight; y++){
for (int x = 0; x < pictureWidth; x++){
inputColor[y][x] = malloc(sizeof(color));
}
}
// Here i am copying values from an inputStream to the structure
int pixel = 0;
for (int y = 0; y < pictureHeight; y++){
for (int x = 0; x < pictureWidth; x++){
inputColor[y][x]->red = inputMalloc[pixel];
pixel++;
inputColor[y][x]->green = inputMalloc[pixel];
pixel++;
inputColor[y][x]->blue = inputMalloc[pixel];
pixel++;
}
}
But it fails again in the first line...
How can a 2-dimensional struct array be allocated with malloc
, so the picture sizes don't matter that much any more?
Right now it fails around a picture size of 700x700 pixels.
color (*inputColor)[pictureWidth] = malloc(pictureHeight * sizeof *inputColor);
. use it withinputColor[y][x].red
... – mch