문제

I have a structure

typedef struct s_var_types_tag
{
    uint8_t type;
    union {
     s_t1_t t1_data;
     s_t2_t t2_data;
     s_t3_t t3_data;
    }
} s_var_types_t;

I have a function pointer

void (*xkey_to_type[MAX_TYPES])(s_x1_t *x1key, s_var_types_t *val);

I want to use this function pointer and utilize the type of data and call the specific pointer to it i.e

s_var_types_t* obj;
Suppose obj type has been set (obj->type = t1)
xkey_to_type[obj->type](x1key,obj)

In this function I want to set specifics of the type If obj type is t1,I can access t1_data as though other components don't exist.

obj->t1_data.a =  xxx;

But it shows me an error saying that the

request for memberin something not a structure or union

Is something wrong?

도움이 되었습니까?

해결책

First, give your union a name:

union {
 s_t1_t t1_data;
 s_t2_t t2_data;
 s_t3_t t3_data;
} my_union;

Then, you can access its fields:

obj->my_union.t1_data.a =  xxx;

다른 팁

What you are using is called an "anonymous union". This is a new feature that appeared in C11. If you don't use that you'll have to name your union member.

union {
 s_t1_t t1_data;
 s_t2_t t2_data;
 s_t3_t t3_data;
} u;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top