【问题标题】:print address of dynamic memory, stored in an array of pointers动态内存的打印地址,存储在指针数组中
【发布时间】:2013-05-16 14:38:44
【问题描述】:

如何打印存储在char* 数组中的数据[在C 中,我们使用%p 来显示地址]。

char * tokens[5];
for(int i=0;i<5;i++)
tokens[i] = new char[5];

for(int i=0;i<5;i++)
std::cout<<"Address: "<<tokens[i]<<std::endl;

/*Add data in the array*/

for(int i=0;i<5;i++)
delete[] tokens[i];

这给了我,

Address: 
Address: 
Address: 
Address: 
Address: 

我知道这一定是因为,tokens[i] 是字符串的起始地址,所以cout 打印出现在为空的字符串。

我必须将tokens[i] 转换为std::cout 吗?

【问题讨论】:

    标签: c++ pointers g++ dynamic-memory-allocation


    【解决方案1】:

    operator&lt;&lt;char* 重载,它假定您有一个要打印的以空字符结尾的字符数组。将其转换为 void* 以获取指针的值:

    std::cout << "Address: " << static_cast<void*>(tokens[i]) << std::endl;
    

    在此处查看运行代码:https://ideone.com/9Cst8F

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多