Reputation: 1
hello lets say i have this code
typedef struct entry {
union {
struct A {
char *c;
} *A;
struct B {
char *c;
} *B;
} value;
} *TableEntry;
i m doing a malloc for entry and now i want to copy a string to c from struct A . do i have to allocate memory for struct A and then for c or the first malloc for table entry allocates for all of them ? thank you in advance
Upvotes: 0
Views: 1100
Reputation: 141618
To clarify, three allocs are needed, e.g.:
TableEntry *t = malloc(sizeof *t);
t->A = malloc(sizeof *t->A);
t->A->c = malloc(50);
This design is questionable though, as there is no way of telling which is currently active out of A
or B
. You will have to have another index or something which keeps track of whether this entry is an A
or a B
.
Upvotes: 0
Reputation: 20272
When you allocate the TableEntry
- you allocate the memory for the whole union. Pointers in it are allocated, but what they point to - are not. So you should assign values that you allocate to c
members of the struct and A
/B
members of the union.
Note that the A
and B
share the same space.
Upvotes: 2