Dereferencing a pointer means accessing the value stored at the memory address that the pointer is pointing to. In C, the * (asterisk) operator is used for dereferencing a pointer.
Upon dereferencing a pointer, the operation retrieves and returns the value stored in the variable to which the pointer points.
Why do we dereference pointers?
- It allows access to and manipulation of the data stored at the memory location pointed to by the pointer.
- Any operation applied to the dereferenced pointer directly affects the value of the variable it points to.
To illustrate the process of dereferencing a pointer, consider the following steps:
- Declare an integer variable ‘point’ to which the pointer will point.
int point= 9;
- Declare an integer pointer variable ‘ptr’.
int *ptr;
- Assign the address of variable ‘point’ to the pointer variable ‘ptr’.
ptr = &point;
- Change the value of variable ‘point’ by dereferencing the pointer ‘ptr’.
*ptr = 8;
The above line modifies the value of variable ‘point’ from 9 to 8 because ‘ptr’ points to the location of ‘point,’ and dereferencing ‘ptr’ (i.e., *ptr = 8) updates the value of ‘point.’
Combining all the steps into a program:
#include <stdio.h>
int main() {
int point = 9; // Declare an integer variable 'point'.
int *ptr; // Declare an integer pointer variable 'ptr'.
ptr = &point; // Assign the address of variable 'point' to the pointer variable 'ptr'.
*ptr = 8; // Change the value of variable 'point' by dereferencing the pointer 'ptr'.
printf("The value of point is: %d", point); // Print the updated value of 'point'.
return 0;
}
Output
The value of point is: 8
Let take another example
#include <stdio.h>
int main() {
int Digit = 43; // Declaration of an integer variable 'Digit'.
int* ptr = &Digit; // Declaration of an integer pointer 'ptr' pointing to the address of 'Digit*'.
// Output the memory address of 'Digit' using the pointer (e.g., 0x7ffe5367e044).
printf("Memory address of Digit: %p\n", ptr);
// Dereference the pointer to output the value of 'Digit' (e.g., 43).
printf("Value of Digit: %d\n", *ptr);
return 0;
}
Output
Memory address of Digit: 0x7ffe5367e044
Value of Digit: 43