gpt4 book ai didi

c - 具有另一个结构指针的结构的深拷贝

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:21 25 4
gpt4 key购买 nike

我正在尝试将一个结构的内容复制到另一个临时结构,这样我就可以在不影响结果的情况下更改临时结构的 RGB 像素(如果我改为更改全局像素)。

代码 结构

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

}

}

想法:glob 结构保存图像宽度、高度和像素*数据,它是指向 R、G、B 值数组的指针。

我想将全局复制到临时,所以当我更改 temp->data 的 RGB 时,它不会影响当前正在执行的代码,并且将 RGB 更改为 global->data 的 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);

我必须释放任何东西吗?

最佳答案

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

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

关于c - 具有另一个结构指针的结构的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com