Referencing pointer
- Siddharth Sharma
- Nov 7, 2024
- 2 min read
Referencing a pointer involves working with the address of a pointer itself or assigning a pointer to another pointer. In C and C++, you can use multiple levels of pointers to create pointers to pointers. This concept enables referencing a pointer itself, not just the value it points to.
How Referencing a Pointer Works
In simple terms:
A single-level pointer (e.g., int* ptr) points to the address of a regular variable.
A pointer to a pointer (e.g., int** ptr2) holds the address of another pointer.
Why Use Pointer-to-Pointer (Referencing Pointers)?
Pointer-to-pointer referencing is useful when you need to modify a pointer itself within a function, or when managing multi-dimensional arrays and complex data structures. It’s also helpful for dynamic memory management where you want a function to modify a pointer directly.
Example of Referencing a Pointer in C
Here's a basic example demonstrating referencing pointers:
#include <stdio.h>
int main() {
int num = 10; // A regular integer variable
int* ptr = # // ptr is a pointer to an integer, holding the address of num
int** ptr2 = &ptr; // ptr2 is a pointer to a pointer, holding the address of ptr
// Displaying values and addresses
printf("Value of num: %d\n", num); // Outputs 10
printf("Value at ptr (num): %d\n", *ptr); // Outputs 10
printf("Value at ptr2 (ptr): %d\n", **ptr2); // Outputs 10
// Displaying addresses
printf("Address of num: %p\n", (void*)&num); // Address of num
printf("Address held by ptr: %p\n", (void*)ptr); // Same as address of num
printf("Address held by ptr2: %p\n", (void*)ptr2); // Address of ptr
// Modifying num using ptr2
**ptr2 = 20;
printf("Modified value of num: %d\n", num); // Outputs 20
return 0;
}Explanation of the Code:
int num = 10; declares a regular integer variable num.
int* ptr = # creates a pointer ptr that holds the address of num.
int** ptr2 = &ptr; creates a pointer-to-pointer ptr2 that holds the address of ptr.
**ptr2 = 20; dereferences ptr2 twice to access num indirectly and modifies it to 20.
Output:
Value of num: 10
Value at ptr (num): 10
Value at ptr2 (ptr): 10
Address of num: [address of num]
Address held by ptr: [address of num]
Address held by ptr2: [address of ptr]
Modified value of num: 20Summary
ptr is a pointer to num.
ptr2 is a pointer to ptr (a pointer-to-pointer).
Referencing pointers allows for multiple levels of indirection, which can be essential for functions that need to modify pointers directly or handle complex data structures.


Comments