Convert long int * to long long int *

On my platform, long int and long long int are the same (64 bits). I have a pointer to a long int, and I want to convert it to a pointer to a long long int. Following code

static_cast<long long int*>(pointer);

is not allowed. What is the correct way to do this in C ++ 11?

+4
source share
2 answers

You need to force the "reinterpretation" of the pointer:

reinterpret_cast<long long int*>(pointer);

" , , ". , reinterpret_cast, , .. .., valgrind .

, , . .. ​​ (, - ..).

:

template <typename Dest, typename Src>
Dest* safe_pointer_cast(Src* src)
{
  static_assert(sizeof(Src) == sizeof(Dest), "size of pointed values differ");
  static_assert(alignof(Src) == alignof(Dest), "alignment different");
  return reinterpret_cast<Dest*>(src);
}
+6

:

long* ptr = /***/;
long long extra_storage = *ptr;
long long* long_ptr = &extra_storage;

, :

static_assert(sizeof(long) == sizeof(long long));
long* ptr = /***/;
long long* long_ptr = reinterpret_cast<long long*>(ptr);
+1

All Articles