C++: Does using dereference to change value of a variable result in that variable pointing to a different memory block?
Solution 1:
The address of a variable never changes during its lifetime.
This means that changing a variable's value, either directly:
a = 2;
Or indirectly:
b = &a;
*b = 2;
Never changes its address. So your first mental model is correct.
Also, this statement is incorrect:
assume variable a points to the memory address
a
is not a pointer type so it does not point to an address. Like all variables, it has an address that does not change.
Solution 2:
The variable a
is not moved through the memory. The memory for the variable a
is allocated as soon as it is defined.
The variable a
points nowhere. It is designed to store an object of the type int
.
It is the pointer b
that stores the address of the variable a
int* b = &a;
So dereferencing the pointer we get an access to the memory allocated for the variable a
and can change the stored object in this memory.
Here is a demonstration program that can help to make understanding easy.
#include <stdio.h>
int main( void )
{
int a = 1;
printf( "The address of the variable a is %p\n", ( void * )&a );
int *b = &a;
printf( "The address stored in the variable b is %p\n", ( void * )b );
*b = 2;
printf( "After the assignment the address of the variable a is %p\n", ( void * )&a );
}
The program output might look like
The address of the variable a is 006FF9D4
The address stored in the variable b is 006FF9D4
After the assignment the address of the variable a is 006FF9D4
As you can see after the assignment
*b = 2;
the address of the variable a
was not changed. It is the value that is stored in the memory occupied by the variable a
that was changed.
You may consider a variable as a named extent of memory designed to store objects of the specified type used to declare the variable.