在c ++

时间:2015-05-28 02:26:57

标签: c++ pointers hex decimal

我试图找到数组元素的内存地址,但输出结果是十六进制。如果你能告诉我如何将它转换为十进制输出,我将不胜感激。

这是代码,

#include<iostream>
using namespace std;

 int main()
  {
   int a[4];

   cout << "Address of a[0] = " << &a << endl;
   cout << "Address of a[1] = " << &a[1] << endl;
   cout << "Address of a[2] = " << &a[2] << endl;
   cout << "Address of a[3] = " << &a[3] << endl;

   cin.get();

   return 0;
  }

1 个答案:

答案 0 :(得分:2)

在C ++ 11中,您可以转换为uintptr_t,例如

cout << "Address of a[0] = " << static_cast<uintptr_t>(&a) << endl;

类型uintptr_t专门用于表示任何可能的指针,因此解决方案是可移植的。

我不知道C ++ 98/03中的可移植解决方案,尽管经常size_t转换为(but not always)。相关:Converting a pointer into an integer

编辑

查看http://en.cppreference.com/w/cpp/types/integer以及C ++标准 18.4.1 Header&lt; cstdint&gt;概要[cstdint.syn] ,看起来uintptr_t可选。我不知道是否有一个实现没有定义它,为什么会选择不定义它。欢迎提出任何意见。