Amarth Gûl
Amarth Gûl

Reputation: 1080

Comparing pointer value passed into a function by address with null resulting in reversed result

I am well aware that there are many similar questions, but have not yet find the one that solves this. So I will also thank anyone that could point me to the duplicate.

Say I have a function that takes a void pointer and modify the value inside:

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

And I passed a NULL pointer by address into it:

void *setList = NULL;

func(&setList);

It would give me not null, which is not what I want. (if passing by value it works well)

What was I missing? How could I judge if it's a NULL pointer when passed by address?

Thanks.

Upvotes: 1

Views: 98

Answers (2)

0___________
0___________

Reputation: 67546

void *setList = NULL;

you create the variable setlist having the type of pointer to void and initialize it to NULL.

func(&setList);

you pass the address of the variable setList not the value of it. The variable is the valid object and its address is by definition not NULL.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

In this declaration

void *setList = NULL;

you declared the variable setList that occupies a memory. So the address of the variable itself is not equal to NULL. It is the value of the variable that is stored in the allocated for the variable memory that is equal to NULL.

In this call

func(&setList);

the type of the argument expression is void **.

Within the function declared like

int func(void *head);

you have at first cast the pointer head to the type void **.

For example

void **p = ( void ** )head;

and then in the if statement you need to dereference the pointer p like

if ( *p == NULL )
//...

Here is a demonstrative program.

#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;
}

Its output is

p is a null pointer
p is not a null pointer

As for your original code then a question arises why is not the function declared like

int func(void **head);

if you are going to pass a pointer to pointer?

Upvotes: 1

Related Questions