C语言 void *输入函数丢失函数结束时的地址



我是C lang的新手。我的代码就像:

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值中的地址仅在函数中,当函数超过变量的值仍然为空...因此,我想要结构中的数组上的指针。

我应该如何解决?

像这样的修复

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

您使用指针传递变量,必须在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) {...}
    ...
}

最新更新