What is the proper cast from void* to long?

Viewed 142

I'm using posix_memalign (had trouble with align_alloc) to allocate (inside my own new) so I have a void*. I need it as int for instance to compute alignment:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main() {

  void *ptr;
  auto align{4096}, size{10000};
  posix_memalign( &ptr,align,size );
  cout << ptr << endl; // works
  cout << ptr % align << endl; // not

  return 0;
}

I thought in modern C++ static_cast<long> would be the right way , but that gives an error that that's not allowed on a void*. So what is the proper way? I can of course use old-style C casts, but I'm trying to avoid those.

2 Answers

You can't static_cast a pointer to a non-pointer type. You may have to use reinterpret_cast:

reinterpret_cast<long>(ptr);

Also since you want to get a pointer address as an integer, it's better to use intptr_t present in stdint.h (which is made for this purpose):

reinterpret_cast<intptr_t>(ptr);

to just print the address

std::cout << "Pointer address = 0x" << void_pointer_var << std::endl;

presuming void_pointer_var is of type void*, this will print its value in hex.

if its relevant for it to be in decimal then use a reinterpret cast

Related