0

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

timrau
  • 22,578
  • 4
  • 51
  • 64

3 Answers3

3

you have to allocate memory for both of them

2

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.

littleadv
  • 20,100
  • 2
  • 36
  • 50
0

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.

M.M
  • 138,810
  • 21
  • 208
  • 365