'copy data from one structure to another in C

If I have a structure defined like:

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

And 2 variables of this type:

struct image image1;
struct image image2;

I want to transfer the data from image1 to the data of image2(presuming image1 has some data written, and image2 has data allocated with malloc or calloc). How can it be done? Thanks a lot.



Solution 1:[1]

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;
}

Solution 2:[2]

did you try memcpy(&image1,&image2,sizeof(image));

edit: Alocate data for image2.data after that you have to strcpy(image2.data,image1.data) if data is null terminated, but if its not, then use memcpy with the size of data.

Regards, Luka

Solution 3:[3]

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

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Luka Pivk
Solution 3 Jomu
Solution 4 Oriol Roma