C 函数结束时,函数的Void*输入将丢失地址
我是C语言的新手。我的代码如下:C 函数结束时,函数的Void*输入将丢失地址,c,pointers,types,C,Pointers,Types,我是C语言的新手。我的代码如下: int afunc(const struct datas *mydata, void *value) { value = &mydata->astring; // astring is in structure char[20] return 0; } int main (...) { ... const char *thevalue; if (!afunc(thedata, &thevalue)
int afunc(const struct datas *mydata, void *value) {
value = &mydata->astring; // astring is in structure char[20]
return 0;
}
int main (...) {
...
const char *thevalue;
if (!afunc(thedata, &thevalue) {...}
...
}
var值中的地址仅在函数中,当函数超过变量时,该值仍然为空。。。所以,我想要结构中数组上的指针
我应该如何解决这个问题?您使用指针来传递必须在C中修改的变量。但是,如果您要修改指针值,必须向该指针传递指针,然后在函数中取消引用该指针。像这样:
int afunc(const struct datas *mydata, void **value) {
*value = &mydata->astring; // astring is in structure char[20]
return 0;
}
int main (...) {
...
const char *thevalue;
if (!afunc(thedata, &thevalue) {...}
...
}
像这样修理
#include <stdio.h>
struct datas {
char astring[20];
};
int afunc(const struct datas *mydata, void *value) {
*(const char **)value = mydata->astring;
return 0;
}
int main (void) {
struct datas mydata = { "test_data" }, *thedata = &mydata;
const char *thevalue;
if (!afunc(thedata, &thevalue)) {
puts(thevalue);
}
}
#包括
结构数据{
char astring[20];
};
int afunc(常量结构数据*mydata,void*值){
*(const char**)value=mydata->astring;
返回0;
}
内部主(空){
struct datas mydata={“test_data”},*thedata=&mydata;
常量字符*值;
如果(!afunc(数据和值)){
卖出(价值);
}
}
您正在传递一个void*
变量,然后您正在覆盖该变量。。。如果要将数据保存到指针指向的位置,可以考虑取消引用。如果你想保存一个指针,考虑使用<代码>空白**/COD>指针(比代码:>代码> *值=和MyDATAB->收敛< <代码> > <代码> *(const char **)值=MyDATA- > AcsIn;< /代码>谢谢你这么多家伙…BLULYXY你的解决方案正是我需要的…