简体   繁体   English

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

[英]How to store int pointer in void*?

Scenario is as follows: 方案如下:

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

I would expect, that the x->val is of type void* (when used in printf() ). 我希望x->val的类型为void* (在printf() )。 How can I get back that int value I stored into it? 如何获取存储在其中的int值?

The problem is in fun If you expect 5 on STDOUT than this function should look like this: 问题很fun如果您希望STDOUT上为5,则此函数应如下所示:

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

You should not return pointer to automatic variable because it's allocated on stack and deferred after function executions. 您不应该返回指向自动变量的指针,因为它是在堆栈上分配的,并在函数执行后被延迟。 To get more info look at this answer 要获取更多信息,请查看此答案

The problem is that the pointer is set to a local variable. 问题在于指针被设置为局部变量。 So when the function terminates, it's memory will be de-allocated, thus the pointer will be set to garbage (it will become a dangling pointer as Hans suggested). 因此,当函数终止时,它的内存将被取消分配,因此该指针将被设置为垃圾(如汉斯所建议的那样,它将成为悬空的指针 )。

So if you are lucky, the printf() will print garbage, if not, then it will print 5. 因此,如果幸运的话, printf()将打印垃圾,否则,将打印5。


A quick fix would be to add the static keyword to int a , which make it not to be de-allocated when the function gets terminated. 一个快速的解决方案是将static关键字添加到int a ,这使它在函数终止时不会被取消分配。

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

However this is not very flexible, because all the instances of fun() will have the same variable a . 但是,这不是很灵活,因为fun()所有实例都将具有相同的变量a

Or you could dynamically allocate memory like this: 或者,您可以像这样动态分配内存:

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

Don't forget to free your memory like this: 不要忘记像这样释放您的记忆:

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

  printf ("%d", *((int*)(x->val)));
  free(x->val);  // this has to go first
  free(x);
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM