Converting a Pointer into an Integer
In a situation where a void* argument needs to be converted into a suitable type, it's crucial to ensure compatibility across different machine architectures.
On a 64-bit machine, casting a void* to an int may result in precision loss. To address this, a modern C approach involves using reinterpret_cast
Correct Integer Type:
To store a pointer as an integer correctly, the appropriate type is uintptr_t or intptr_t, defined in
Correct Casting Operator:
In C , reinterpret_cast is the preferred cast for pointer conversions. Avoid using the C cast.
Example:
#include <cstdint> void *p; std::uintptr_t i = reinterpret_cast<std::uintptr_t>(p);
Related Questions:
The above is the detailed content of How can I safely convert a void* pointer to an integer in C ?. For more information, please follow other related articles on the PHP Chinese website!