Linux 将整数类型转换为 void*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16016920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:42:51  来源:igfitidea点击:

type casting integer to void*

clinuxpointerspthreadsvoid-pointers

提问by

#include <stdio.h>
void pass(void* );
int main()
{
    int x;
    x = 10;
    pass((void*)x);
    return 0;
}
void pass(void* x)
{
   int y = (int)x;
   printf("%d\n", y);
}


output: 10

my questions from the above code..

我从上面的代码中提出的问题..

  1. what happens when we typecast normal variable to void* or any pointer variable?

  2. We have to pass address of the variable to the function because in function definition argument is pointer variable. But this code pass the normal variable ..

  1. 当我们将普通变量类型转换为 void* 或任何指针变量时会发生什么?

  2. 我们必须将变量的地址传递给函数,因为在函数定义中参数是指针变量。但是这段代码传递了普通变量..

This format is followed in linux pthread programming... I am an entry level C programmer. I am compiling this program in linux gcc compiler..

这种格式在linux pthread编程中遵循...我是一个入门级的C程序员。我正在 linux gcc 编译器中编译这个程序..

采纳答案by Some programmer dude

I'm only guessing here, but I think what you are supposed to do is actually pass the addressof the variable to the function. You use the address-of operator &to do that

我只是在这里猜测,但我认为您应该做的实际上是将变量的地址传递给函数。您使用 address-of 运算符&来做到这一点

int x = 10;
void *pointer = &x;

And in the function you get the value of the pointer by using the dereference operator *:

在函数中,您可以使用取消引用运算符获取指针的值*

int y = *((int *) pointer);

回答by Tarantula

Please read why glibprovide macros for this kind of conversions, there's no need to repeat the text here. The main point is: a pointer has a platform dependent size.

请阅读为什么 glib为此类转换提供宏,此处无需重复文本。要点是:指针具有平台相关的大小。

回答by Giacomo Tesio

If you are planning to use pthreadsand you are planning to pass the passfunction to pthread_create, you have to malloc/freethe arguments you are planning to use (even if the threaded function just need a single int).

如果您打算使用pthreads并且打算将pass函数传递给pthread_create,则必须使用malloc/free您打算使用的参数(即使线程函数只需要一个 int)。

Using an integer address (like &x) is probably wrong, indeed each modification you will execute on xwill affect the passbehaviour.

使用整数地址(如&x)可能是错误的,实际上您将执行的每个修改x都会影响pass行为。