Home  >  Article  >  Backend Development  >  How can I safely convert a void* pointer to an integer in C ?

How can I safely convert a void* pointer to an integer in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 10:52:02647browse

How can I safely convert a void* pointer to an integer in C  ?

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. This ensures a portable and efficient conversion.

Correct Integer Type:

To store a pointer as an integer correctly, the appropriate type is uintptr_t or intptr_t, defined in for C99 or the std namespace for C 11.

  • C 11 (and onwards): std::uintptr_t
  • C 03: uintptr_t (wrapped in extern "C" { if necessary})
  • C99: uintptr_t

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:

  • What is the uintptr_t data type?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn