user3187860
user3187860

Reputation: 1

Struct inside union inside struct in c

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

Answers (3)

M.M
M.M

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

littleadv
littleadv

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

user3520514
user3520514

Reputation: 88

you have to allocate memory for both of them

Upvotes: 3

Related Questions