c - 如何在 void* 中存储 int 指针?

标签 c pointers casting

场景如下:

typedef struct a {
    void* val;
} a_t;

void fun (void** val)
{
    int a = 5;
    *val = &a;
}

a_t *x;
x = malloc (sizeof *x);
fun (&x->val);

printf ("%d", *((int*)(x->val)));

我希望 x->valvoid* 类型(在 printf() 中使用时)。我怎样才能取回我存储在其中的 int 值?

最佳答案

问题出在fun 如果您期望 STDOUT 上有 5 个,则此函数应如下所示:

void fun (void** val)
{
    int *a = malloc(sizeof(int));
    *a = 5;
    *val = a;
}

您不应该返回指向自动变量的指针,因为它在堆栈上分配并在函数执行后延迟。要获得更多信息,请查看 this answer

关于c - 如何在 void* 中存储 int 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948187/

相关文章:

json - sqlalchemy/postgres : arithmetic on JSON fields?

c - 警告 : initialisation from incompatible pointer type via function table in c

c - cat.c 中 #if 0 的用途

c - 获取RHEL6内核代码

复合文字和指针

C# 将数组转换为元素类型

c - 使用 sizeof 查找 argv 中字符串的大小

C 变量和指针

c++ - 我很困惑为什么我的 fillDeck 函数说, "assigning to ' char *' from incompatible type ' const char *”

Oracle Cast 和 MULTISET 在 POSTGRES 中可用