比较按地址传递给函数的指针值是否为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,这不是我想要的。 (如果按值传递则效果很好)

我想念什么?通过地址传递时,如何判断它是否为NULL指针?

谢谢。

解决方法

在此声明中

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);

如果要将指针传递给指针?

,
void *setList = NULL;

您创建类型为setlist的变量pointer to void并将其初始化为NULL。

func(&setList);

您传递变量setList的地址而不是它的值。该变量是有效对象,并且根据定义,其地址不是NULL。