0

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;
    }
}
2
  • very confusing: you have to defined STRUCT1 and STRUCT2 then you can use Commented Dec 5, 2012 at 8:03
  • You'd probably need to have a case for STRUCT3 using s3 = t_struct.obj[j].s_obj.s3;, presumably. Commented Dec 5, 2012 at 8:08

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Yes, I misplaced that when I copied the code. Already fixed, Thanks.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.