Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning a struct?

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?

like image 462
gator Avatar asked Dec 06 '25 02:12

gator


1 Answers

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);
like image 134
Tamás Zahola Avatar answered Dec 08 '25 16:12

Tamás Zahola