空指针解引用 [英] void pointer dereferencing

查看:113
本文介绍了空指针解引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
取消引用无效指针

我有一个这样的函数调用:

I have a function call this way:

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

I am typecasting it back to int in the function to use it. Am I dereferencing it wrong inside the foo() function?

推荐答案

if((int *)context ==1)

你想要这个:

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

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

You were casting to a pointer to int but what you actually want is to actually access the int so you need to dereference the pointer.

这篇关于空指针解引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆