c++中cout输出字符串首地址

来源:互联网 发布:没学历学编程难吗 编辑:程序博客网 时间:2024/06/09 19:38
char *p="hello";cout<<p;

在我们的印象中此时会输出字符串的首地址,然而此时cout会直接将字符串输出,而不是字符串的首地址,而在c语言中printf("%p",p);就会输出字符串数组的首地址,printf("%s",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;}

对于其他类型的数组不会出现此种情况:
     int a[] = { 1, 2, 3 };     cout << a << endl;     printf("%p\n",a);
输出的都是数组的首地址。


0 0
原创粉丝点击