cerr cerr - 2 months ago 8
C Question

How do I pass a member of a union by reference

I have a union declared like:

typedef union {
mpls_vpls_t Vpls_dat; //typedef struct
mpls_vpws_t Vpws_dat; //typedef struct
}ser_cache_t;


and I allocate memory for it:

ser_dat_ch = calloc(LABEL_T_CNT,sizeof(ser_cache_t));
if (ser_dat_ch == NULL)
return ERROR;


while
static ser_cache_t *ser_dat_ch = NULL;
is global.

Now I want to populate my union with data and hence I wantto pass a pointer to it to a function like:

rv = switch_mpls_vpws_data_get(lab, &ser_dat_ch->Vpws_dat[lab]);


But here the compiler screams: expression must have pointer-to-object type
why so, won't
&ser_dat_ch->Vpws_dat[lab]
resolve to the address I'm looking for?

Answer

I assume you have an array of such unions and one pointer to the start of that memory. Then, accessing one of the ith element's structure member would look like

ser_dat_ch[i].Vpws_dat

and a pointer to that union is

&(ser_dat_ch[i])

and a pointer to one of the structs in the union (that is apparently what you're looking for) is

&(ser_dat_ch[i].Vpws_dat)
Comments