gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:21 24 4
gpt4 key购买 nike

场景如下:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com