Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dereferencing structure from (void *) type

i'm trying to pass data with void pointer and then cast it to (pData *) type. What am i doing wrong? gcc gives me

gcc test.c error: request for member ‘filename’ in something not a structure or union

typedef struct data {
        char *filename;
        int a;
} pData;

void mod_struct(void *data) {
        printf("%s\n",(pData *)data->filename); //error on this line
}

void main() {
        pData *data;
        data = (pData *) malloc(sizeof(pData));
        data->filename = (char *)malloc(100);
        strcpy(data->filename,"testing testing");
        data->a=1;
        mod_struct((void *)&data);
}
like image 441
damir Avatar asked Mar 21 '11 23:03

damir


2 Answers

Should be

printf("%s\n", ((pData *) data)->filename);

-> operator has higher precedence than typecast operator.

In addition to that your call to mod_struct should look as follows

mod_struct((void *) data);

That & you have there makes absolutely no sense. Why are you taking the address of data when data is already a pointer to what you need?

like image 136
AnT Avatar answered Sep 30 '22 16:09

AnT


(pData *)data->filename is equivalent to (pData *)(data->filename); add parens if you want it to be ((pData *)data)->filename.

Also, BTW, your code will crash. You're passing a pData ** cast to void *, and then casting it back to a pdata *.

like image 31
Anomie Avatar answered Sep 30 '22 14:09

Anomie