Search code examples
cscanfpass-by-reference

Why does adress-of operator work in scanf?


int a = 5;
int *ptr_a = &a;

If I change the ptr_a pointer with normal assignment, i.e. ptr_a = 6, it will change the ptr_a address it points to.

But why does it work on scanf?

scanf("enter a value", &a);

My logic is that since &a == ptr_a, any assignment to &a will behave like we assign any number to ptr_a.

So, can someone explain why assign to &var in scanf work?


Solution

  • To change an object passed to a function you need to pass it by reference.

    In C passing by reference means passing an object indirectly through a pointer to it. So dereferencing the pointer you will get a direct access to the original object and can change it.

    In this call of scamf

    scanf("enter a value", &a);
    

    the original object a is passed by reference. So the function scanf can change the object by dereferencing the passed pointer that points to the original object. It is not the pointer that is changed. It is the variable pointed to by the pointer that is changed.

    Consider the following demonstration program.

    #include <stdio.h>
    
    void f1( int x )
    {
        x = 10;
    }
    
    void f2( int *px )
    {
        *px = 10;
    }
    
    int main( void ) 
    {
        int a = 0;
    
        printf( "Before calling f1 a = %d\n", a );
        f1( a );
        printf( "After  calling f1 a = %d\n", a );
    
        putchar( '\n' );
    
        printf( "Before calling f2 a = %d\n", a );
        f2( &a );
        printf( "After  calling f2 a = %d\n", a );
    }
    

    . The program output is

    Before calling f1 a = 0
    After  calling f1 a = 0
    
    Before calling f2 a = 0
    After  calling f2 a = 10
    

    The function f1 deals with a copy of the value of the original variable a because it is passed by value.

    The function f2 has a direct access to the original variable a by dereferencing the parameter of the pointer type because the variable a is passed by reference.