【问题标题】:void pointer dereferencing [duplicate]void指针取消引用[重复]
【发布时间】:2012-12-29 01:32:31
【问题描述】:

可能重复:
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() 函数中解引用错了吗?

【问题讨论】:

    标签: c pointers void-pointers


    【解决方案1】:
    if((int *)context ==1)
    

    你想要这个:

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

    您正在转换为指向int 的指针,但您真正想要的是实际访问int,因此您需要取消引用该指针。

    【讨论】:

      【解决方案2】:

      您没有将其类型转换为int,而是将其类型转换为int *,然后没有取消引用它。试试:

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

      【讨论】:

      • 感谢您的即时回复!所以人们太好了:-)
      【解决方案3】:

      当您想访问该值时,仅投射指针对您没有帮助..

      (*(int*)context == 1) 会解决你的问题..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 2017-11-03
        • 1970-01-01
        • 2012-03-25
        • 2012-05-23
        • 2014-06-01
        相关资源
        最近更新 更多