0

My program

#include <iostream>

using std::cout;
using std::endl;

int main() {

        int a[] = {1, 3, 5, 7, 9};

        for (int i = 0; i < n; i++) {
                int address = &a[i];
                cout << "a[" << i << "] = " << a[i] << " at address " << &a[i] << " = decimal " << address << endl;
        }

}

I want to print array element address in decimal, but above code fails to compile.

I have also tried to print it using

cout << std::dec << &a[i] << endl;

but that does not work too


Answer: Figured it out from

Converting a pointer into an integer

Have to cast the address to reinterpret_cast<std::uintptr_t>

 cout << "a[" << i << "] = " << a[i] << " at address " << &a[i] << " = " << reinterpret_cast<std::uintptr_t>(&a[i]) << endl;
xxx374562
  • 226
  • 1
  • 8
  • There is no guarantee that the address value can fit into an `int` type. There is a `std::uintptr_t` type that should be used instead, however, the standard does not mandate implementations to have that type – WhiZTiM Dec 02 '18 at 10:42
  • Related: https://stackoverflow.com/q/153065/315052 – jxh Dec 02 '18 at 10:43
  • This should do it: `auto address = reinterpret_cast(&a[i]);`. But check the related questions, too. – lubgr Dec 02 '18 at 10:44

0 Answers0