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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With