在C中将数据从一个结构复制到另一个结构

big*_*man 1 c structure memcpy

如果我有一个定义如下的结构:

struct image{
unsigned int width, height;
unsigned char *data;
};
Run Code Online (Sandbox Code Playgroud)

这个类型的2个变量:

struct image image1;
struct image image2;
Run Code Online (Sandbox Code Playgroud)

我想将数据从image1传输到image2的数据(假设image1有一些数据写入,而image2有数据用malloc或calloc分配).怎么做到呢?非常感谢.

hmj*_*mjd 5

假设两个实例struct image指向相同的实例是不可取的,datamemcpy()不能用于复制structs.复印:

  • 为目标结构分配内存
  • data根据源为目标缓冲区分配内存data
  • 指派width成员
  • memcpy() data 成员.

例如:

struct image* deep_copy_image(const struct image* img)
{
    struct image* result = malloc(sizeof(*result));
    if (result)
    {
        /* Assuming 'width' means "number of elements" in 'data'. */
        result->width = img->width;
        result->data = malloc(img->width);
        if (result->data)
        {
            memcpy(result->data, img->data, result->width);
        }
        else
        {
            free(result);
            result = NULL;
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)