简体   繁体   English

以十进制打印变量地址

[英]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. 默认情况下,使用十六进制格式的ostream& operqator<<(ostream&, void*)有一个重载。

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


Please no discussions about the c-style cast. 请不要讨论C型转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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