Pointer to pointer is an reference that contain another pointer memory address. Remember, the reason it’s called pointer because it’s just pointing to another place that have “value”. Pointer is different with pointer to pointer. This is the simple explanation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> #include<str using namespace std; int main() { int customer = 1; int *pointerCustomer; int *pointerToPointerCustomer; pointerCustomer = &customer; // 1 pointerToPointerCustomer = &pointerCustomer; // 2 cout << **pointerToPointerCustomer; // 3 return 0; } |
1. We assign memory address of “customer” into pointerCustomer
2. We assign memory address of “pointerCustomer” to pointerToPointerCustomer
3. We get the value of customer by dereferencing pointerToPointerCustomer.
Now we see how the pointer-to-pointer works. Then let’s reverse a variable array using pointer to pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include<iostream> using namespace std; // Example of reverse array without change the memory address in variable int main() { // Create a new variable array int student[] = {1, 2, 3}; // Create pointer array int *studentPointer[3]; // Pointer to pointer array int **pointerToPointer[3]; int i, j; // Pointer have sequence order of memory address of student for(i=0; i < 3; i++) { cout << student[i]; studentPointer[i] = &student[i]; } cout << "n"; // Reverse for(i=0, j=2; i < 3; i++, j–) { pointerToPointer[j] = &studentPointer[i]; } // Showing result for(i=0; i < 3; i++) { cout << **pointerToPointer[i]; } return 0; } |
What we doing here is we create a variable array, pointer array and pointer-to-pointer array. Then we iterate variable array and assign each element memory-address into pointer.
At reverse step, we iterating pointer and pointer-to-pointer array using increment and decrement at the same time. That mean we put reverse index of pointer into pointer-to-pointer. Then at the end, we show the value by dereference each element in pointerToPointer.