开发者

dereferencing structure from (void *) type

开发者 https://www.devze.com 2023-02-19 00:27 出处:网络
i\'m trying to pass data with void pointer and then cast it to (pData *) type. What am i doing wrong? gcc gives me

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


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?


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


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


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

}


[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.

0

精彩评论

暂无评论...
验证码 换一张
取 消