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
type casting integer to void*
提问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..
我从上面的代码中提出的问题..
what happens when we typecast normal variable to void* or any pointer variable?
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 ..
当我们将普通变量类型转换为 void* 或任何指针变量时会发生什么?
我们必须将变量的地址传递给函数,因为在函数定义中参数是指针变量。但是这段代码传递了普通变量..
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
回答by Giacomo Tesio
If you are planning to use pthreads
and you are planning to pass the pass
function to pthread_create
, you have to malloc
/free
the 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 x
will affect the pass
behaviour.
使用整数地址(如&x
)可能是错误的,实际上您将执行的每个修改x
都会影响pass
行为。