I have some structs like the below:
typedef struct {
GLubyte red, green, blue;
} pixel;
typedef struct {
pixel *pixelData;
int w, h;
} imagen;
It's for an image loader and image processor (applies filters to a loaded image).
I'm initializing two imagen:
imagen work, original;
work is something that I want to display after having some filters applied, and original is something I can reset to.
void loadImage() {
//load data into (imagen)original
}
work = original;
After loading the image, I copy it to work so I can maintain a copy of the original should I want to reset later (reset being work = original again). The problem I'm facing is that the reset doesn't work: anything I apply to work is also applied to original, so I'm effectively resetting to what I'm resetting.
I think the problem is my work = original; I'm fairly new to C, but I'm assuming I'm only pointing work at original, so any logic I do on work is also applied to original?
original.w = 40;
work = original;
work.w = 50;
work = original;
Is work.w 40 or 50 in this case? If it is indeed pointing to original, how do I instead clone original onto work, so I can safely work on work without consequence of original?
You have a pixelData pointer in your struct:
typedef struct {
pixel *pixelData;
int w, h;
} imagen;
In order to create a completely independent copy, you need to copy the data pixelData is pointing to:
work.w = original.w;
work.h = original.h;
size_t size = sizeof(pixel) * work.w * work.h;
work.pixelData = (pixel*)malloc(size);
memcpy(original.pixelData, work.pixelData, size);
Also note that when you no longer need it you have to release the allocated memory:
free(work.pixelData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With