我很清楚有很多类似的问题,但还没有找到解决这个问题的方法。因此,我也将感谢任何能给我指出副本的人。
假设我有一个函数,它接受一个空指针并修改里面的值:
int func(void *head)
{
if (head == NULL){
printf("is nulln");
/* do sth with the value */
}
else{
printf("not nulln");
/* do sth with the value */
}
return 1;
}
我把一个NULL
指针按地址传给它:
void *setList = NULL;
func(&setList);
它会给我not null
,这不是我想要的。(如果按值传递,效果良好(
我错过了什么?当通过地址传递时,我如何判断它是否是NULL
指针?
谢谢。
在此声明中
void *setList = NULL;
您声明了占用内存的变量setList
。因此,变量本身的地址不等于NULL
。存储在分配给变量存储器的中的变量值等于NULL
。
在这次通话中
func(&setList);
自变量表达式的类型是CCD_ 7。
在像一样声明的函数内
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
的变量CCD_ 11并将其初始化为NULL。
func(&setList);
您传递的是变量setList
的地址,而不是它的值。该变量是有效对象,其地址根据定义不是NULL。