【问题标题】:Deep Copy of a struct with another struct pointer具有另一个结构指针的结构的深拷贝
【发布时间】:2013-10-07 21:43:22
【问题描述】:

我正在尝试将一个结构的内容复制到另一个临时结构,这样我就可以在不影响结果的情况下更改临时结构的 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);

}

我必须释放任何东西吗?

【问题讨论】:

  • 为了你自己的理智,我现在告诉你,如果你的dest 已经绑定了一个图像数据集,这将像筛子漏水一样泄漏内存。并且 noither 循环是必需的。一个简单的memcpy() 就足够了。

标签: c memcpy


【解决方案1】:

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

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

【讨论】:

  • 我只是在更改 dest->w 和 dest->h 时遇到内存错误违规。你会用那一行替换最后 4 行吗?
  • @George 更新您的问题并显示调用此函数的代码,包括 source 和@ 的声明 987654324@ 传递给此函数的结构。听起来您有一个未初始化的源、目标或两者。你说“我想将全局复制到一个临时的”这使得正确设置 global 并且不包含不确定值非常重要。
【解决方案2】:

首先:您的 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);

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2010-12-16
    • 2016-12-18
    • 1970-01-01
    • 2011-08-31
    • 2022-01-15
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多