I'd say this is the modern C++ way.
#include <cstdint>
void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);
EDIT:
The correct type to the the Integer
so the right way to store a pointer as an integer is to use the uintptr_t
or intptr_t
types. (See also in cppreference integer types for C99).
these types are defined in <stdint.h>
for C99 and in the namespace std
for C++11 in <cstdint>
(see integer types for C++).
C++11 (and onwards) Version
#include <cstdint>
std::uintptr_t i;
C++03 Version
extern "C" {
#include <stdint.h>
}
uintptr_t i;
C99 Version
#include <stdint.h>
uintptr_t i;
The correct casting operator
In C there is only one cast and using the C cast in C++ is frowned upon (so don't use it in C++). In C++ there is different casts. reinterpret_cast
is the correct cast for this conversion (See also here).
C++11 Version
auto i = reinterpret_cast<std::uintptr_t>(p);
C++03 Version
uintptr_t i = reinterpret_cast<uintptr_t>(p);
C Version
uintptr_t i = (uintptr_t)p; // C Version
Related Questions
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…