c - 将按地址传递给函数的指针值与空值进行比较,导致结果相反
问题描述
我很清楚有很多类似的问题,但还没有找到解决这个问题的问题。因此,我还要感谢任何可以将我指向副本的人。
假设我有一个函数,它接受一个 void 指针并修改里面的值:
int func(void *head)
{
if (head == NULL){
printf("is null\n");
/* do sth with the value */
}
else{
printf("not null\n");
/* do sth with the value */
}
return 1;
}
我通过NULL
地址将指针传递给它:
void *setList = NULL;
func(&setList);
它会给我not null
,这不是我想要的。(如果按值传递效果很好)
我错过了什么?NULL
通过地址传递时如何判断它是否是指针?
谢谢。
解决方案
在这份声明中
void *setList = NULL;
setList
您声明了占用内存的变量。所以变量本身的地址不等于NULL
。存储在为变量分配的内存中的变量值等于NULL
。
在这次通话中
func(&setList);
参数表达式的类型是void **
。
在声明为的函数内
int func(void *head);
您首先将指针head
转换为 type void **
。
例如
void **p = ( void ** )head;
然后在 if 语句中,您需要取消引用指针p
,例如
if ( *p == NULL )
//...
这是一个演示程序。
#include <stdio.h>
int func( void *head )
{
void **p = ( void ** )head;
if ( *p == NULL )
{
puts( "p is a null pointer" );
}
else
{
puts( "p is not a null pointer" );
}
return 1;
}
int main(void)
{
void *setList = NULL;
func( &setList );
int x = 10;
setList = &x;
func( &setList );
return 0;
}
它的输出是
p is a null pointer
p is not a null pointer
至于您的原始代码,那么就会出现一个问题,为什么函数没有声明为
int func(void **head);
如果你要传递一个指向指针的指针?
推荐阅读
- office-js - Office 插件身份验证
- javascript - 为什么我的代码在等待语句之后不执行?
- python - 使用 Python 对类似图像的数据执行图像裁剪
- php - PHP:从字符串集中递归增强数组
- php - 如何为我的 laravel eloquent DB::table 选择别名表?
- reactjs - 在 React js 中将功能组件转换为类组件
- bluespec - 寄存器大小的向量不能由模块参数参数化
- azure - 使用 azure devops 部署 webjob
- reactjs - 如何通过 Windows 身份验证详细信息来响应应用程序
- python - tweepy - ModuleNotFoundError