1

I was trying to find the memory address of an array elements but the output is turning out to be in Hexadecimal. I would appreciate if u could tell me how to convert it to a Decimal output.

Here is the Code,

#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;
  }
vsoftco
  • 55,410
  • 12
  • 139
  • 252
Manav Saxena
  • 453
  • 2
  • 8
  • 21
  • `cout << "Address of a[0] = " << std::dec << (int) &a << endl;` – karlphillip May 28 '15 at 02:31
  • @karlphillip `int` may not be large enough, especially if you address more than 2GB RAM and `int` is 32 bit. And in any case, I don't think it is portable, although it does the job most of the time. – vsoftco May 28 '15 at 02:35
  • At least the compiler lets you know if it's not big enough. *error: cast from pointer to smaller type 'int' loses information* – chris May 28 '15 at 02:44

1 Answers1

2

In C++11 you can cast to uintptr_t, like

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

The type uintptr_t is specifically designed to represent any possible pointer, so the solution is portable.

I am not aware of a portable solution in C++98/03, although a cast to size_t often (but not always) works. Related: Converting a pointer into an integer.


EDIT

Looking at http://en.cppreference.com/w/cpp/types/integer and also at the C++ standard 18.4.1 Header <cstdint> synopsis [cstdint.syn], it looks like uintptr_t is optional. I have no idea whether there is an implementation that does not define it, and why would one chose to not define it. Any comments are welcome.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • See http://stackoverflow.com/q/1464174/1553090 for caveats to your last statement. – paddy May 28 '15 at 02:37
  • @paddy yes I know, also http://stackoverflow.com/q/153065/3093378 discusses the issue, that's why I said that I'm not aware of a portable solution. Thanks for the link though, I have added it to the edited response. – vsoftco May 28 '15 at 02:38
  • Writing the address in hex to an ostringstream that GMP then parses and outputs in decimal is one portable approach, but it'd be crazy not to first see if `uintptr_t` had the required portability over implementations of interest. – Tony Delroy May 28 '15 at 03:55
  • @TonyD sure, or [Boost.Multiprecision](http://www.boost.org/doc/libs/1_58_0/libs/multiprecision/doc/html/index.html) ;) I start liking the latter more and more, it's really easy to use. – vsoftco May 28 '15 at 04:04