How it works when assigning a pointer * to a pointer **?

Viewed 114

I am learning about pointers. when i practice assigning pointer * by pointer ** then p_to_p = ptr but *p_to_p != *ptr. Here is my practice code

#include <iostream>

using namespace std;

int main()  {
    
    int value = 100;
    int *ptr = &value;
    int **p_to_p = (int**)ptr;

    cout << p_to_p << "   " << ptr << endl; 
    cout << *p_to_p << "   " << *ptr << endl; 

    return 0;
}

Please explain how it works when assigning pointers * to pointers **. Thank you very much!

3 Answers
int **p_to_p = (int**)ptr;

Here, you reinterpret the value of ptr as a int**. All object pointers can be reinterpreted as pointers of other types, but you generally may not indirect through such reinterpreted poiters except for rare cases.

*p_to_p

This is not such exceptional case. The behaviour of the program is undefined.

int **p_to_p = (int**)ptr;

is a typecast. A reinterpret one.

What you probably want is the same you did on the line before:

int **p_to_p = &ptr;

Taking the address of a pointer gives you a pointer to a pointer.

By declaring a variable as int **, you are defining a pointer to an integer pointer. So you should assign the address of the integer pointer to it. You can do this way:

int **p_to_p = &ptr;
cout << **p_to_p << endl; 
Related