2013-10-07 231 views
1

我想将一个结构的内容复制到另一个结构temp,所以我可以在不影响结果的情况下改变temp结构的RGB像素(如果我改变了全局像素) 。一个结构与另一个结构指针的深拷贝

代码 的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; 

我复制代码

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)) 

     } 

} 

的想法:圆顶封装结构保持图像的宽度,高度和像素*数据是一个指针R的阵列, G,B值。

我想复制全局到临时,所以当我改变温度 - >数据的RGB时,它不会影响当前正在执行的代码,并且基于将全局 - >数据的RGB更改为RGB。

新代码

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); 

}

我一定释放什么?

+0

为了您自己的理智,我现在告诉您,如果您的'dest'已经有一个图像数据集绑定到它,这将会像筛漏水一样泄漏内存。 * *不需要*循环。一个简单的'memcpy()'就足够了。 – WhozCraig

回答

2

您多次拨打memcpy(w * h)。我建议你只复制一次

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

当我更改dest-> w和dest-> h时,我只是得到内存错误违规。你会用这一行代替最后4行? – George

+0

是的,摆脱两个for循环 –

+0

添加编辑原始,仍然错误 – George

0

第一:你的API不是很合作。通过分配dest-> data,您可能会覆盖其之前的内容,因此:泄漏内存。如果你唯一的目的是复制结构对象(使用深拷贝),这将是恕我直言,更稳健,以实现这个像一个DUP操作:

glob * dup_the_Pic(glob *src) { 
glob * dst; 

    dest = malloc (sizeof *dst); 
    // maybe check for malloc failure here 
    memcpy (dst,src, sizeof *dst); 

    dst->data = malloc(dst->w * dst->h * sizeof *dst->data); 
    // maybe check for malloc failure here, too 
    memcpy(dst->data, src->data, dst->w * dst->h * sizeof *dst->data); 

return dst; 
} 

被称为像:

glob *the_original, *the_copy; 

the_original = read_thing_from_file(...); 

the_copy = dup_the_Pic(the_original); 
do_stuff_with_the_pic(the_copy); 
相关问题