1

如果我的结构定义如下:

struct image{
unsigned int width, height;
unsigned char *data;
};

和这种类型的 2 个变量:

struct image image1;
struct image image2;

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

4

5 回答 5

5

Assuming it is undesirable that two instances of struct image are pointing to the same data then memcpy() cannot be used to copy the structs. To copy:

  • allocate memory for destination struct
  • allocate memory for destination data buffer based on source data
  • assign width members
  • memcpy() data members.

For example:

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;
}
于 2013-05-03T14:07:44.137 回答
2

你试过 memcpy(&image1,&image2,sizeof(image));

编辑:为 image2.data 分配数据,如果数据为空终止,则必须 strcpy(image2.data,image1.data) ,但如果不是,则使用 memcpy 和数据大小。

问候,卢卡

于 2013-05-03T14:05:20.800 回答
2
struct image image1;
struct image image2;

...

image2.width = image1.width;
image2.height = image1.height;

/* assuming data size is width*height bytes, and image2.data has enough space allocated: */

memcpy(image2.data, image1.data, width*height);
于 2013-05-03T14:08:30.170 回答
1

It's simple in C.Simply do the following(assuming image2 is uninitialized):

image2=image1;  //there's no deep copy, pointed to memory isn't copied

You can assign one structure variable to other given they are of the same type.No need to copy piece-meal.This is a useful feature of C.

This has been discussed before :

Assign one struct to another in C

于 2013-05-03T14:07:55.470 回答
1

如果您想要的只是复制结构(即创建“浅”副本):

image2 = image1;

如果您还想复制(“深拷贝”)指向的数据image1.data,那么您需要手动执行此操作:

memcpy(image2.data, image1.data, image1.width * image1.height);

(假设数据中有image1.width * image1.height字节,并且有足够的空间malloc()image2.data存储它。)

于 2013-05-03T14:08:44.633 回答