Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast pointer address to int

Tags:

c++

Beginner question: How can I take the adress of a pointer and save it as an int? Example:

int *ptr = xyz;
int i = static_cast<int>(ptr);

So if ptr points to the memory adress 123, i should be 123. My compiler says it's an error: invalid static_cast from type 'int*' to type 'int'.

Guess I am missing something but I don't know what.

like image 684
chris342423 Avatar asked Dec 05 '22 07:12

chris342423


1 Answers

You can use reinterpret_cast. An int is not guaranteed to be able to losslessly store a pointer though, so you should use the std::intptr_t type instead.

like image 117
user3175411 Avatar answered Dec 09 '22 14:12

user3175411