我想将一个结构的内容复制到另一个结构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);
}
我一定释放什么?
为了您自己的理智,我现在告诉您,如果您的'dest'已经有一个图像数据集绑定到它,这将会像筛漏水一样泄漏内存。 * *不需要*循环。一个简单的'memcpy()'就足够了。 – WhozCraig