Search code examples
arrayscpointersimplicit-conversionpass-by-value

Why does the char pointer not get updated to NULL


'''

void calling (char *str)
{

    str = NULL;
    
}

int main()
{
    char str2[20];
    calling(str2);

    if(str2 == NULL)
    {
        printf("null");
    }


    return 0;
}

'''

Just wondering why did the printf not run.Can I not change the char-array pointer to NULL once its declared.


Solution

  • For starters you have an array

    char str2[20];
    

    that is str2 is not a pointer it is an array. Arrays are non-modifiable lvalues. You can not assign one array to another array like for example

    char str1[20];
    char str2[20];
    
    str1 = str2;
    

    In this function call

    calling(str2);
    

    the array designator str2 is implicitly converted to pointer to the first element of the array and represents an rvalue. You can imagine the function definition and its call the following way

    calling(str2);
    
    //...
    
    void calling ( /*char *str*/)
    {
        char *str = str2;
        str = NULL;
    
    }
    

    As you can see the function deals with a copy of the value of an expression that yields the value of the address of the first element of the array str2.

    Within the function it is the local variable (pointer) str that is changed. The original array str2 declared in main stays unchanged.

    Even if you will pass the array by reference you will be unable to change it. For example this program will not compile

    #include <stdio.h>
    
    void calling (char ( *str )[20] )
    {
    
        *str = NULL;
        
    }
    
    int main()
    {
        char str2[20];
        calling( &str2 );
    
        if(str2 == NULL)
        {
            printf("null");
        }
    
    
        return 0;
    }
    

    because in this statement

        *str = NULL;
    

    you are trying to assign a pointer to an array.