将通过地址传递给函数的指针值与 null 进行比较,结果相反
Comparing pointer value passed into a function by address with null resulting in reversed result
我很清楚有很多类似的问题,但还没有找到解决这个问题的人。因此,我还要感谢任何可以将我指向副本的人。
假设我有一个函数,它接受一个 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
,这不是我想要的。 (如果按值传递,效果很好)
我错过了什么? address传递时如何判断是不是NULL
指针?
谢谢。
在此声明中
void *setList = NULL;
你声明了占用内存的变量setList
。所以变量本身的地址不等于NULL
。它是存储在分配给变量内存中的变量值,等于NULL
.
在本次通话中
func(&setList);
参数表达式的类型是void **
。
在声明为 like
的函数中
int func(void *head);
您首先将指针 head
转换为类型 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);
如果要将指针传递给指针?
void *setList = NULL;
您创建了类型为 pointer to void
的变量 setlist
并将其初始化为 NULL。
func(&setList);
你传递的是变量的地址 setList
而不是它的值。该变量是有效对象,其地址根据定义不为 NULL。
我很清楚有很多类似的问题,但还没有找到解决这个问题的人。因此,我还要感谢任何可以将我指向副本的人。
假设我有一个函数,它接受一个 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
,这不是我想要的。 (如果按值传递,效果很好)
我错过了什么? address传递时如何判断是不是NULL
指针?
谢谢。
在此声明中
void *setList = NULL;
你声明了占用内存的变量setList
。所以变量本身的地址不等于NULL
。它是存储在分配给变量内存中的变量值,等于NULL
.
在本次通话中
func(&setList);
参数表达式的类型是void **
。
在声明为 like
的函数中int func(void *head);
您首先将指针 head
转换为类型 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);
如果要将指针传递给指针?
void *setList = NULL;
您创建了类型为 pointer to void
的变量 setlist
并将其初始化为 NULL。
func(&setList);
你传递的是变量的地址 setList
而不是它的值。该变量是有效对象,其地址根据定义不为 NULL。