以十进制打印变量地址

Printing the addresses of variables in decimal

我试图以十进制而不是六进制打印数组元素的地址,但它不起作用。下面是代码和输出示例。

#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;
}

输出示例:

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

ostream& operqator<<(ostream&, void*) 有一个默认使用十六进制格式的重载。

cout << setw(9) << (long long)&arr[i] ... 应该可以解决问题。


请不要讨论 c 风格转换。

更好更便携的方式是:-

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