2012-12-29 113 views
1

可能重复:
Dereferencing void pointers空指针引用

我有一个函数调用这种方式:

void foo(void *context) //function prototype 
.. 
.. 
.. 
main() 
{ 
. 
. 
foo(&(ptr->block)); //where ptr->block is of type integer. 
. 
. 
. 
void foo(void *context) 
{ 
Here I try to use the ptr->block but am having problems. I have tried 

if((int *)context ==1) 
    .. 
    .. 
} 

我类型转换它放回功能的int用它。我是否在foo()函数内解引用它错误?

回答

5
if((int *)context ==1) 

你想这个代替:

if(*(int *)context ==1) 

你被强制转换为指针int,但你真正想要的是实际访问int所以你需要取消引用指针。

+0

真棒!感谢:-) – mane

3

您没有将其转换为int,您将它转换为int *,然后不对其进行解引用。尝试:

if (*(int *)context == 1) 
+0

感谢您的即时回复!所以人们太好了:-) – mane

0

当你要访问的价值,只是投放指针不会帮助你..

(*(int*)context == 1)将解决您的问题..