dereferencing structure from (void *) type

damir picture damir · Mar 22, 2011 · Viewed 7.3k times · Source

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

Answer

AnT picture AnT · Mar 22, 2011

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?