It is useful to understand relationship between pointers and integers. They all can be represented as numbers and converted back and forth. Let's look at following example:
int main()
{
// pointer to int64_t
int64_t* pointer = new int64_t(5);
// an integer keeping address of the pointer in decimal format
int64_t pointerAsNumber = (int64_t) pointer;
// pointer to int64_t created from int64_t integer
int64_t* pointerFromNumber = (int64_t*)pointerAsNumber;
// both print 5 - number stored in memory cell with address "pointer"
cout << *pointer << endl;
cout << *pointerFromNumber << endl;
// both print same number - the address of memory cell that stores number 5
// the printed numbers may differ between different program runs
cout << pointer << endl;
cout << pointerFromNumber << endl;
// print address of the memory cell that holds 5 in decimal format
cout << pointerAsNumber << endl;
// print address of the memory cell that holds 5 in hexadecimal format
// note, all 4 printed numbers, pointer, pointerFromNumber, pointerAsNumber and
//(hex) << pointerAsNumber are same numbers
cout << (hex) << pointerAsNumber << endl;
// now three DIFFERENT numbers will be printed
// they hold addresses of pointer, pointerFromNumber and pointerAsNumber
cout << &pointer << endl;
cout << &pointerFromNumber << endl;
cout << &pointerAsNumber << endl;
}
I find specially useful possibility to convert user defined data types to and from integers.
Here is another example:
struct MyStruct {
int a;
int b;
MyStruct(int a_, int b_) : a(a_), b(b_) {}
};
int main()
{
MyStruct* ms = new MyStruct(1,2);
// storing address of ms in msaddr ;
uint64_t msaddr = (uint64_t)ms;
// creating another MyStruct from the address
MyStruct* ms2 = (MyStruct*)(msaddr);
// the both MyStruct keep same numbers
cout << ms->a << endl;
cout << ms->b << endl;
cout << ms2->a << endl;
cout << ms2->b << endl;
// but they are different structs in memory
cout << &ms << endl;
cout << &ms2 << endl;
}
Keep in mind, the demonstrated possibilities of converting between integers and pointers are not recommended and should be used with great caution, when at all.