Search code examples
cstructunionsdynamic-arrays

Dynamic array with struct that contains a union in C


I'm kind of new to C, so please bear with me. I have a struct that contains union of other structs with variable sizes like this:

typedef struct _obj_struct {
    struct_type type;
    union obj {
        struct1 s1;
        struct2 s2;
        struct3 s3;
    } s_obj;
} obj_struct;

typedef struct _t_struct {
    unsigned int number_of_obj;
    obj_struct* objs;
    other_struct os;
    unsigned int loop;
} t_struct;

The struct_type is the type of the struct we use in the union. How do I go through all elements in the objs? Is this the right way to do this:

struct1 s1;
struct2 s2;
struct3 s3;

for (j=0; j<t_struct.number_of_obj; j++)
{
    switch (t_struct.obj[j].type) {
        case STRUCT1:
            s1 = t_struct.objs[j].s_obj.s1;
            break;
        case STRUCT2:
            s2 = t_struct.objs[j].s_obj.s2;
            break;
    }
}

Solution

  • Unless you need the copy of each structure, use pointers instead:

    struct1 *s1;
    // ...
    s1 = &t_struct.objs[j].s_obj.s1;
    

    Please note, that you have to specify an element of the union as well.