首页 > 解决方案 > 将按地址传递给函数的指针值与空值进行比较,导致结果相反

问题描述

我很清楚有很多类似的问题,但还没有找到解决这个问题的问题。因此,我还要感谢任何可以将我指向副本的人。

假设我有一个函数,它接受一个 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通过地址传递时如何判断它是否是指针?

谢谢。

标签: cfunctionpointerspass-by-reference

解决方案


在这份声明中

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

如果你要传递一个指向指针的指针?


推荐阅读