I have the following struct in my C program
struct person {
char key[50];
char color[20];
int age;
};
I want to make a deep copy of this struct. I've got my deep copy function setup however I'm a bit confused about how to deep copy strings. I've heard of people using strcpy
and others using strdup
.
What I want in my program is for the deep copied person's key and color not to be affected if the original person is freed. Once set, the key and color cannot change. For my purpose, should I be using the strcpy
or strdup
function?
The simplest way to copy a character array to another character array is to use memcpy. If you want to copy all elements of array src of size m to array dst of size n, you can use the following code. char src[m]; char dst[n];
The point to note is that the array members are not shallow copied, compiler automatically performs Deep Copy for array members..
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.
Using the inbuilt function strcpy() from string. h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.
Post-K&R (i.e. in standard C) you can just assign them. The function below is just to make the example clear, you would always just assign in-place:
void deepCopyPerson(struct person *target, struct person *src)
{
*target = *src;
}
To elaborate: The char arrays are part of your struct object (true arrays, not only pointers!), and as such are allocated and copied with the object.
In order to satisfy the disbeliefers ;-) I dug around in the standard draft 1570 :
6.5.16 Assignment operators
Semantics
An assignment operator stores a value in the object designated by the left operand. [Followed by type conversion and sequencing considerations which are not relevant here.]
[...]
6.5.16.1 Simple assignment
Constraints
One of the following shall hold:
[...]
the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right;
[...]
Semantics
In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
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