I'm trying to make an image 4 times its size by making a temp image, with double the original images width and height.Then take information from each pixel on the original image and give it to 4 pixels on the temp image. Something like this.
Original image:
[1] [2]
[3] [4]
To temp image:
[1][1] [2][2]
[1][1] [2][2]
[3][3] [4][4]
[3][3] [4][4]
But I get an access violation writing location 0xCDCDCDCD. Here is my function code:
void makeBigger(Image* plain)
{
Image temp;
temp.height = plain->height * 2;
temp.width = plain->width * 2;
temp.pixels = (Pixel**)malloc(sizeof(Pixel*) * temp.height);
for (int i = 0, k = 0; i < temp.height; i+2, k++)
{
temp.pixels[i] = (Pixel*)malloc(sizeof(Pixel) * temp.width);
for (int j = 0, g = 0; j < temp.width; j+2, g++)
{
temp.pixels[i][j].r = plain->pixels[k][g].r;
temp.pixels[i][j+1].r = plain->pixels[k][g].r;
temp.pixels[i+1][j].r = plain->pixels[k][g].r;
temp.pixels[i+1][j+1].r = plain->pixels[k][g].r;
temp.pixels[i][j].g = plain->pixels[k][g].g;
temp.pixels[i][j+1].g = plain->pixels[k][g].g;
temp.pixels[i+1][j].g = plain->pixels[k][g].g;
temp.pixels[i+1][j+1].g = plain->pixels[k][g].g;
temp.pixels[i][j].b = plain->pixels[k][g].b;
temp.pixels[i][j+1].b = plain->pixels[k][g].b;
temp.pixels[i+1][j].b = plain->pixels[k][g].b;
temp.pixels[i+1][j+1].b = plain->pixels[k][g].b;
}
}
*plain = temp;
}
On the violation seems to occur on the line
temp.pixels[i+1][j].r = plain->pixels[k][g].r;
as that is when the program breaks and the error shows. What is causing this violation and why? What can be done to fix this?
Inside the outer loop, at every iteration:
temp.pixels[i]
to point to a properly allocated memory blocktemp.pixels[i]
temp.pixels[i+1]
But since you do not initialize temp.pixels[i+1]
to point to a properly allocated memory block, attempting to access memory with this variable leads to a memory access violation (or more generally, undefined behavior).