If both first
and second
have the same type, then you can just do second = first;
. It does not matter whether the type is an built-in or user-defined. C will copy the contents of first
over to second
. Just try it.
In general, variables in C are just data with a name and a type.
If the types of 2 variables a
and b
match, you can assign one to the other: a = b;
.
What happens is that the value of variable b
is copied into variable a
.
But beware of pointers: For C, pointers are just variables with a value (the fact that the value represents a memory address does not matter, C treats all data equal).
If the 2 variables happen to be pointers, like char *a; char *b;
then you can assign a = b;
just with any variable.
But since the value of the variable b
is the memory address, the memory address is copied from b
to a
, not the content of the memory at the memory address.
If you want to have the memory copied over, you will have to do it on your own, e.g. via the help of memcpy()
(see its man page for information).
That said, if your structs contain pointers, the pointers are the content, not the stuff the pointers point to. C would copy the pointer values, not the pointer targets.
If you got pointers in your structs and want some sort of deep-copy, you would have to implement the traversal of your structs on your own. See What is the difference between a deep copy and a shallow copy?