打印数组元素的内存不会忽略C和C ++,为什么不同的输出? [英] Printing array element memory adresses C and C++, why different output?

查看:105
本文介绍了打印数组元素的内存不会忽略C和C ++,为什么不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/5657123/how-to-simulate-printfs-p-format-when-using-stdcout\">How使用的std ::当模拟的printf的%P格式COUT?

我试着打印出C和C ++中的数组元素的内存地址。

I try to print out the array element memory addresses in C and C++.

在C:

char array[10];
int i;
for(i =0; i<10;i++){
    printf(" %p \n", &array[i]);
}

我得到的内存地址: 0xbfbe3312 0xbfbe3313 0xbfbe3314 ...

但是,如果我试图在C ++一样的:

But if I try to make the same in C++:

char array[10];
for(int i =0; i<10;i++){
    std::cout<<&array[i]<<std::endl;
}

我得到这样的输出:

I got this output:

点结果
  结果
  

P��
��

K结果
  结果
  

  

k�



为什么会不同?我应该使用 COUT 不同的方式在C ++来打印出内存地址?我应该如何打印出内存地址?

Why is it different? Should I use the cout differently in C++ to print out the memory addresses? How should I print out the memory addresses?

推荐答案

在打印前铸地址无效* ,在C ++中的运营商的LT; &LT; 的ostream 的过载为(常量)字符* ,使其认为它是C风格的字符串:

Cast the address to void* before printing, in C++ the operator<< of ostream is overloaded for (const) char* so that it thinks it's a c-style string:

char array[10];
for(int i =0; i<10;i++){
    std::cout << static_cast<void*>(&array[i]) << std::endl;
}

另请参阅<一个href=\"http://stackoverflow.com/questions/5657123/how-to-simulate-printfs-p-format-when-using-stdcout\">this矿山的答案。

这篇关于打印数组元素的内存不会忽略C和C ++,为什么不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆