Examples of Pointer Dereferencing
Example 1:
Using a pointer to access and modify the value of an integer variable.
C
// C Program to illustrate the dereferencing of pointer #include <stdio.h> int main() { // Declare integer variable number int num = 10; // Declare pointer to store address of number int * ptr = # // Print the value of number printf ( "Value of num = %d \n" , num); // Print Address of the number using & operator printf ( "Address of num = %d \n" , &num); // Print Address stored in the pointer printf ( "Address stored in the ptr = %p \n\n" , ptr); printf ( "Dereference content in ptr using *ptr\n\n" ); // Access the content using * operator printf ( "Value of *ptr = %d \n" , *ptr); printf ( "Now, *ptr is same as number\n\n" ); printf ( "Modify the value using pointer to 6 \n\n" ); // Modify the content in the address to 6 using pointer *ptr = 6; // Print the modified value using pointer printf ( "Value of *ptr = %d \n" , *ptr); // Print the modified value using variable printf ( "Value of number = %d \n" , num); return 0; } |
Output
Value of num = 10 Address of num = 0x7ffe47d51b4c Address stored in the ptr = 0x7ffe47d51b4c Dereference content in ptr using *ptr Value of *ptr = 10 Now, *ptr is same as number Modify the value using pointer to 6 Value of *ptr = 6 Value of number = 6
Example 2: Dereferencing Double Pointer
The double pointers can also be dereferenced using the same logic but you will have to use the indirection operator two times: One for moving to the pointer the double pointer is pointing to and the other for accessing the actual value.
C
// C program to dereference double pointer #include <stdio.h> int main() { int var = 10; int * ptr = &var; // double pointer int ** dptr = &ptr; // dereferencing the double pointer printf ( "Accesing value from double pointer using " "**dptr: %d" , **dptr); return 0; } |
Output
Accesing value from double pointer using **dptr: 10
Just like that, we can dereference pointers of any level.
Dereference Pointer in C
We know that the pointer variable can store the memory address in C language and in this article, we will learn how to use that pointer to access the data stored in the memory location pointed by the pointer.
Contact Us