What is the proper cast from void* to long?

Vic*_*out 2 c++ casting dynamic-memory-allocation

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;
}
Run Code Online (Sandbox Code Playgroud)

我认为在现代C ++ static_cast<long>中将是正确的方法,但这会导致错误,这是不允许的void*。那么正确的方法是什么?我当然可以使用旧式的C强制类型转换,但我正在尝试避免使用这些类型。

D. *_*ael 9

您不能static_cast指向非指针类型的指针。您可能需要使用reinterpret_cast

reinterpret_cast<long>(ptr);
Run Code Online (Sandbox Code Playgroud)

另外,由于您希望将指针地址获取为整数,因此最好使用intptr_tpresent in stdint.h(为此目的而设计):

reinterpret_cast<intptr_t>(ptr);
Run Code Online (Sandbox Code Playgroud)