As we already know that "what is a pointer", a pointer is a variable that stores the address of another variable. The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be returned.
Why we use dereferencing pointer?
Dereference a pointer is used because of the following reasons:
- It can be used to access or manipulate the data stored at the memory location, which is pointed by the pointer.
- Any operation applied to the dereferenced pointer will directly affect the value of the variable that it points to.
Let's observe the following steps to dereference a pointer.
- First, we declare the integer variable to which the pointer points.
- Now, we declare the integer pointer variable.
- After the declaration of an integer pointer variable, we store the address of 'x' variable to the pointer variable 'ptr'.
- We can change the value of 'x' variable by dereferencing a pointer 'ptr' as given below:
The above line changes the value of 'x' variable from 9 to 8 because 'ptr' points to the 'x' location and dereferencing of 'ptr', i.e., *ptr=8 will update the value of x.
Let's combine all the above steps:
printf("value of x is : %d", x);
Let's consider another example.
printf("The value of x is : %d",x);
printf("\n The value of y is : %d",y);
In the above code:
- We declare two variables 'x' and 'y' where 'x' is holding a '4' value.
- We declare a pointer variable 'ptr'.
- After the declaration of a pointer variable, we assign the address of the 'x' variable to the pointer 'ptr'.
- As we know that the 'ptr' contains the address of 'x' variable, so '*ptr' is the same as 'x'.
- We assign the value of 'x' to 'y' with the help of 'ptr' variable, i.e., y=*ptr instead of using the 'x' variable.
Note: According to us, if we change the value of 'x', then the value of 'y' will also get changed as the pointer 'ptr' holds the address of the 'x' variable. But this does not happen, as 'y' is storing the local copy of value '5'.
Let's consider another scenario.
printf("The value of a is : %d",a);
In the above code:
- First, we declare an 'a' variable.
- Then we declare two pointers, i.e., ptr1 and ptr2.
- Both the pointers contain the address of 'a' variable.
- We assign the '7' value to the *ptr1 and '6' to the *ptr2. The final value of 'a' would be '6'.
Note: If we have more than one pointer pointing to the same location, then the change made by one pointer will be the same as another pointer.