cerr cerr - 1 year ago 45
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

and I allocate memory for it:

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

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
resolve to the address I'm looking for?

Answer Source

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


and a pointer to that union is


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