damir damir -4 years ago 47
C Question

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");
mod_struct((void *)&data);

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download