我很清楚有很多类似的问题,但还没有找到解决这个问题的方法。所以我也要感谢任何能给我指出副本的人。
假设我有一个函数,它接受一个空指针并修改里面的值:
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指针?
谢谢。
发布于 2020-10-20 06:36:51
在本声明中
void *setList = NULL;您声明了占用内存的变量setList。因此,变量本身的地址不等于NULL。它是存储在中的变量的值,分配给等于NULL的变量内存。
在此呼叫中
func(&setList);参数表达式的类型为void **。
在声明如下的函数中
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);如果你要把一个指针传递给指针?
发布于 2020-10-20 06:51:37
void *setList = NULL;创建类型为pointer to void的变量setlist,并将其初始化为NULL。
func(&setList);传递的是变量setList的地址,而不是它的值。该变量是有效的对象,其地址根据定义是not NULL。
https://stackoverflow.com/questions/64435914
复制相似问题