版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Compile_the_life/article/details/45894883
-
char *p=
"hello";
-
cout<<p;
c++语言中的解决方案:
用void*指向字符串,cout无法知道void*指针指向的数据的解析方法,所以会输出字符串的首地址,而在我们的印象中数组的名字,就是数组中元素的首地址。
-
#include <iostream>
-
#include <string>
-
-
using
std::
cin;
-
using
std::
cout;
-
using
std::
endl;
-
using
std::
string;
-
-
int main()
-
{
-
char ch1[] = {
'a',
'b',
'c' };
-
char ch2[] = {
'a',
'b',
'c',
'\0' };
-
char ch3[] =
"abc";
-
char *ch = ch2;
-
printf(
"%p\n",ch2);
//C语言方式输出数组的首地址
-
cout << ch2 <<
endl;
//我们意识中应该输出数组的首地址,实际输出的是指针指向的字符串
-
printf(
"%p\n",ch);
-
cout << ch <<
endl;
-
cout << &ch <<
endl;
//这种形式输出的是数组首地址的存放地址
-
printf(
"%p\n",&ch);
-
-
/*解决方法*/
-
void *ch11 = ch2;
-
printf(
"%p\n",&ch2);
-
cout << ch11 <<
endl;
-
-
getchar();
-
return
0;
-
}
![](https://i-blog.csdnimg.cn/blog_migrate/ced8c5e5a69b04eb2ab9c45df1b79bca.png)
对于其他类型的数组不会出现此种情况:
-
int a[] = {
1,
2,
3 };
-
cout << a <<
endl;
-
printf(
"%p\n",a);
输出的都是数组的首地址。