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

の 2 つのインスタンスが同じを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;
}
于 2013-05-03T14:07:44.137 に答える
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

構造体を複製することだけが必要な場合(つまり、「浅い」コピーを作成する場合):

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 に答える