Search code examples
cmemcpy

Deep Copy of a struct with another struct pointer


I am trying to copy the contents of one struct to another temp struct so i can alter the RGB pixels of the temp struct without affecting the outcome (if i altered the global pixels instead).

Code Structs

//the pixel structure
typedef struct {
    GLubyte r, g, b;
} pixel;

//the global structure
typedef struct {
    pixel *data;
    int w, h;
} glob;
glob global, original, temp;

my copy Code

void copyPic(glob *source, glob *dest){
    int x,y;
    dest -> w = source -> w;
    dest -> h = source -> h;
    dest -> data = (pixel *) malloc(dest->w * dest->h * sizeof(pixel*));
    for (x=0; x < dest -> w; x++)
        for (y=0; y < dest -> h; y++){
            memcpy(dest->data[x+y*dest->w], source->data[x+y*dest->w], sizeof(pixel))

        }

}

The idea: the glob struct holds the image width, height and pixel* data which is a pointer to an array of R,G,B values.

I want to copy the global to temporary so when i change the RGB of temp->data it doesnt affect the code that is currently executing and basing changing the RGB off the RGB of global->data.

New Code

void copyPic(glob *src, glob *dest){

dest -> w = src -> w;
dest -> h = src -> h;
dest -> data = (pixel *) malloc(dest->w * dest->h * sizeof(pixel));

memcpy(dest->data, src->data, sizeof(pixel) * dest->w  * dest->h);

}

Do i have to free anything?


Solution

  • You are calling memcpy many times (w * h). I would suggest that you copy only once

    memcpy(dest->data, source->data, sizeof(pixel) * w * h);