4

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.

timrau
  • 22,578
  • 4
  • 51
  • 64
chris342423
  • 439
  • 1
  • 6
  • 22

3 Answers3

14

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.

user3175411
  • 1,002
  • 7
  • 13
  • Okay thanks, ofcourse its reinterpret_cast... I tried dynamic_cast but totally forgot about reinterpret_cast. Sometimes I wake up and don't remember my name. Okay I made this one up but seriously, how could I forget that? ;) I know that pointers and ints can have different sizes but it does not matter for what I do. – chris342423 Feb 01 '14 at 16:09
  • @chris342423: if you are on a 64 bits machine, using `int` means you'll almost never see the real address. – Matthieu M. Feb 01 '14 at 18:02
2

You can also use C-style casting:

int *ptr = xyz;
int i = (int) ptr;

Here's a nice discussion comparing C-style casting to reinterpret_cast.

Community
  • 1
  • 1
1''
  • 26,823
  • 32
  • 143
  • 200
0

you can use the following function to get any pointer as unsigned long. int is not guaranteed to fulfill the task.

template <typename T>
static constexpr inline auto ptrToAddr(T *pointer) noexcept
{
  return reinterpret_cast<std::uintptr_t>(pointer);
}