Dereferencing a pointer is necessary for the following reasons:
- It enables access to or modification of the data located at the memory address indicated by the pointer.
- Any action performed on the dereferenced pointer will have a direct impact on the value of the variable it points to.
Let's review the subsequent actions required to dereference a pointer.
Initially, we define the integer variable that the pointer is referencing.
int x =9;
- Next, we define the integer pointer variable.
After defining an integer pointer variable, the address of the 'x' variable is assigned to the pointer variable 'ptr'.
ptr=&x;
To modify the value of variable 'x', we can update it through dereferencing a pointer 'ptr' using the following syntax:
*ptr =8;
The preceding statement adjusts the value of variable 'x' from 9 to 8 by utilizing a pointer 'ptr' that references the memory location of 'x'. When 'ptr' is dereferenced as *ptr=8, it effectively modifies the value stored in 'x'.
Let's combine all the above steps:
#include <stdio.h>
int main()
{
int x=9;
int *ptr;
ptr=&x;
*ptr=8;
printf("value of x is : %d", x);
return 0;}
Output
[Program Output]
Let's consider another example.
#include <stdio.h>
int main()
{
int x=4;
int y;
int *ptr;
ptr=&x;
y=*ptr;
*ptr=5;
printf("The value of x is : %d",x);
printf("\n The value of y is : %d",y);
return 0;
}
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'.
Output
[Program Output]
Let's consider another scenario.
#include <stdio.h>
int main()
{
int a=90;
int *ptr1,*ptr2;
ptr1=&a;
ptr2=&a;
*ptr1=7;
*ptr2=6;
printf("The value of a is : %d",a);
return 0;
}
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.
Output