You cannot just dereference pointers if they are not pointing to anything valid.
To be able to do x->u
you have to make sure x
points to some valid memory, The code you show dereferences an uninitialized pointer which causes an Undefined Behavior and most likely a crash. Same applies for y->u
. So make sure x
and y
point to valid memory before you dereference them.
x->u = y->u
Will not perform a deep copy but a shallow copy.
You will basically end up with two pointers pointing to the same memory, which is not probably what you intend or need.
If you need a deep copy, you should allocate your destination enough memory to hold the data being copied to it and then use memcpy
to copy the contents of the source union to it.
Good Read:
What is the difference between a deep copy and a shallow copy?