Printing the addresses of variables in decimal

核能气质少年 提交于 2020-01-11 11:25:09

问题


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

回答1:


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.




回答2:


Better and portable way would be :-

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


来源:https://stackoverflow.com/questions/27888101/printing-the-addresses-of-variables-in-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!