简体   繁体   中英

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;
    }
}

The t_struct.obj[j].s_obj is the union, not the actual structure. You have to use t_struct.obj[j].s_obj.s1 etc.

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.

While accessing a member of union contained inside a struct, the general syntax is

structVariable.unionVariable.memberName

The way you're accessing is fine if you just add the member name at the end. So the correct version would be:

switch (t_struct.objs[j].type) {
    case STRUCT1:
        s1 = t_struct.objs[j].s_obj.s1;
        break;
    case STRUCT2:
        s2 = t_struct.objs[j].s_obj.s2;
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM