Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure deep copy

This may be a very basic question but somehow it got me tricked... when I write test code, it seems to work, but something is going wrong in production.

// Header file
#define length 100
typedef struct testStr_t {
    int a;
    char b;
    char t1[length];
    char t2[length];
} test;

void populateTest(test*);

// source file
test test1;
test test2;
populateTest(&test1);
test2 = test1;

Will test2 be a deep copy of test1? Or are there gotchas here? Does it matter if the code is compiled with a C compiler or a C++ compiler?

like image 823
Kiran Avatar asked May 23 '11 21:05

Kiran


People also ask

How do you deep copy a struct?

To perform a deep copy you must first free any memory that was being pointed to by the destination structure. Then allocate enough memory to hold the strings pointed to by the source structure. Now, strncpy the strings over. Save this answer.

What is a deep copy?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What is deep and shallow copy?

Shallow Copy stores the references of objects to the original memory address. Deep copy stores copies of the object's value. Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn't reflect changes made to the new/copied object in the original object.

Can struct be copied?

We can also use assignment operator to make copy of struct. A lot of people don't even realize that they can copy a struct this way because one can't do same it with an array. Similarly one can return struct from a function and assign it but not array. The compiler do all the copying stuff behind the scene for us.


1 Answers

Deep copies are only hindered by pointers, so your struct will be copied correctly in C. It'll work in C++ as well unless you define your own operator= that doesn't copy correctly. You only need to define operator= for types with pointers, since a shallow copy of a pointer will copy the pointer but share the data.

like image 57
Chris Lutz Avatar answered Oct 01 '22 02:10

Chris Lutz