简体   繁体   中英

Printing the addresses of variables in decimal

I'm trying to print the addresses of the elments of an array in decimal instead of hexa but it doesn't work. Below is the code and output example.

#include <iostream>
#include <iomanip>
using namespace std;

void printarrandptr(int arr[], int size);
const int LEN = 5;

void main(){

    int arr[LEN] = { 15, 3, 14, 11, 14 };

    int *p[LEN];

    printarrandptr((int*)arr, LEN);
}

void printarrandptr(int arr[], int size){
    int i;

    for (i = 0; i < size; i++)
        cout << setw(9) << &arr[i] << setw(4) << arr[i] << endl;
    cout << endl;
}

output example:

 0098FDC8  15
 0098FDCC   3
 0098FDD0  14
 0098FDD4  11
 0098FDD8  14

Better and portable way would be :-

int arr[2] = {1,2};
uintptr_t number = (uintptr_t)&arr[0];
cout << number << endl;

There's a overload for ostream& operqator<<(ostream&, void*) that uses hex format by default.

cout << setw(9) << (long long)&arr[i] ... should do the trick.


Please no discussions about the c-style cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM