0

I want to store a pointer into a fundamental data type.

My intuition says that the right data type for this is a std::size_t and it works:

#include <fmt/core.h>

int main() {
  int i = 0;
  int* p = &i;
  auto const t = reinterpret_cast<std::size_t>(p);
  fmt::print("size of address: {}\n", sizeof(p));
  fmt::print("size of std::size_t: {}\n", sizeof(t));
  fmt::print("value of address to i: {}\n", static_cast<void*>(p));
  fmt::print("value of std::size_t t: {0:#x}\n", t);
  return *p;
}

https://godbolt.org/z/dWf5W6

And the program outputs:

Program returned: 0
size of address: 8
size of std::size_t: 8
value of address to i: 0x7ffdd754a0dc
value of std::size_t t: 0x7ffdd754a0dc

But is this true for every platform?

How can I be sure?

The Shmoo
  • 358
  • 1
  • 16
  • 1
    See [this C++ reference](https://en.cppreference.com/w/cpp) and use (when available) `std::intptr_t`. On old or exotic hardware, it could be difficult (e.g. on intel286) – Basile Starynkevitch Mar 15 '21 at 06:31
  • Thank you! Somehow I did not found the related questions. I will go with `std::uintptr_t` – The Shmoo Mar 15 '21 at 06:33

0 Answers0