从 (void *) 类型取消引用结构 [英] dereferencing structure from (void *) type
本文介绍了从 (void *) 类型取消引用结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 void 指针传递数据,然后将其转换为 (pData *) 类型.我究竟做错了什么?gcc 给了我
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 错误:在非结构体或联合体中请求成员文件名"
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);
}
推荐答案
应该
printf("%s\n", ((pData *) data)->filename);
->
运算符的优先级高于类型转换运算符.
->
operator has higher precedence than typecast operator.
除此之外,您对 mod_struct
的调用应如下所示
In addition to that your call to mod_struct
should look as follows
mod_struct((void *) data);
你所拥有的 &
完全没有意义.当 data
已经是你需要的指针时,你为什么还要取 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?
这篇关于从 (void *) 类型取消引用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文