The dereference structure of the (void *) type

I am trying to pass data with a void pointer and then drop it (pData *). What am I doing wrong? gcc gives me

Gcc test.c error: querying member file name in something not 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); } 
+6
c void-pointers
source share
4 answers

Must be

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

-> has a higher priority than the typecast statement.

In addition to this, your mod_struct call should look like this

 mod_struct((void *) data); 

There is absolutely no point in this & you. Why do you take the address data when data already a pointer to what you need?

+10
source share

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

In addition, BTW, your code will fail. You pass pData ** to void * and then go back to pdata * .

+4
source share

You pass the pData * pointer to the void * pointer, specifying its address. so you actually throw pData ** on void *, so you need to find it correctly.

 (*(pData**)data)->filename 

or just don’t take the address of the data when you click in the main

 mod_struct((void *)data); 
+2
source share
  #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { char *filename; int a; }pdata; void func(void * data) { printf("%s \n",(*(pdata **)data)->filename); } int main() { pdata *data; void *vptr=0; data=(pdata *)malloc(sizeof(pdata)); data->filename=(char *)malloc(sizeof(50)); vptr=&data; printf("enter the file name \n"); scanf("%s ",data->filename); func(vptr); return 0; 

}

0
source share

All Articles