首页 > 解决方案 > 我可以在哪种基本数据类型中存储地址

问题描述

我想将指针存储到基本数据类型中。

我的直觉说,正确的数据类型是 astd::size_t并且它有效:

#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

程序输出:

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

但对于每个平台都是如此吗?

我怎么能确定?

标签: c++types

解决方案


推荐阅读