c - void * 函数的输入在函数结束时丢失地址

标签 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) {...}
    ...
}

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 - void * 函数的输入在函数结束时丢失地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43577632/

相关文章:

c# - Foo.class 是做什么的?

c - 如何生成大的随机数 C

c - 如果 char[] 位于 struct __attribute__((aligned)) 内部,则 char[] 的步长是否保证为 1?

c - 使用指针的字符串连接中的段错误

c++ - 如何在不强制转换的情况下捕获无符号值?

python - 使用 eval() 创建 numpy.float64

c - 使用 (void *) 作为通用数据容器时的左值问题

c - 指向结构体的指针中的元素数量

java - 如何通过抽象类实现函数指针的 Java 等价物

c - 我是否需要释放一个从函数接收动态分配对象的指针?