Home > Mobile >  Why does adress-of operator work in scanf?
Why does adress-of operator work in scanf?

Time:10-16

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?

CodePudding user response:

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.

CodePudding user response:

What you are missing is that in your first example you can also do

*ptr_a = 6;

which will change the value of a itself and not the address ptr_a points to.

In the same way, passing &a to a function allows that function to change the value of a.

CodePudding user response:

The scanf() function doesn't change the pointer; it takes the inputted value and stores it at the memory address the pointer points to. The pointer (whose value is the address pointed to) remains the same. You can, of course, reassign a value to a pointer (i.e., change the memory address the pointer points to, as opposed to putting a different value at that address) as in your example ptr_a = 6, but it's not at all advisable to do that. That creates undefined behaviour, because you don't know what data is stored at memory address 6.

  • Related