dereferencing structure from (void *) type

假装没事ソ 提交于 2019-12-05 22:28:29

问题


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

回答1:


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?




回答2:


(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 *.




回答3:


You are casting the pData* to a void* pointer by taking the address of it. so you are actually casting pData** to void*, therefore you need to dereference it properly

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

or simple don't take the address of data when you cast in main

mod_struct((void *)data);



回答4:


 #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;

}




回答5:


[TIPS C CODE] @Damir:

  data=(pdata *)malloc(sizeof(pdata));

Should be corrected like this:

data = malloc(sizeof(pdata));

It is unnecessary, as void * is automatically and safely promoted to any other pointer type in this case. In one case : portability. It will probably be good but in your case i don't think so, it was just a tips. you can cast if you want but i think is not necessary.

Under the ANSI C standard, the cast is redundan.

Have a good week end.



来源:https://stackoverflow.com/questions/5385147/dereferencing-structure-from-void-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!