问题
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