I've got a pointer to a struct with a union
so let's say we have
struct A {
union {
char **word;
struct A *B
} u;
};
and I have variables x and y of type A*
typedef A* A_t;
A_t x;
A_t y;
would x->u = y->u be enough to copy over stuff in the union.
Union in C. Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location.
The members of a union are stored in a shared memory area. This is the key feature that allows us to find interesting applications for unions. Consider the union below: There are two members inside this union: The first member, “word”, is a two-byte variable. The second member is a structure of two one-byte variables.
You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.
Consider the union below: There are two members inside this union: The first member, “word”, is a two-byte variable. The second member is a structure of two one-byte variables. The two bytes allocated for the union is shared between its two members. The allocated memory space can be as shown in Figure 1 below.
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?
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