C++中,将char或char[]传给cout进行输出,结果会是整个字符串。如果想要获得字符串的地址(第一个字符的地址),可以使用方法:
强制转化为其他指针(非char),可以是void, float*,int*,double等。使用&s[0]不能输出s[0]的地址,因为&s[0]将返回char,对于char*,cout会将其作为字符串来处理,向下查找字符并输出直到字符结束*。
#include <iostream>
using namespace std;
int main()
{
int * p=new int[3];
cout<<p<<endl;
cout<<*p<<endl;
cout<<&p<<endl;
cout<<(void*)p<<endl;
return 0;
}
输出:
0x22da010
0
0x7fff088258a8
0x22da010
#include <iostream>
using namespace std;
int main()
{
char * p="hello";
cout<<p<<endl;
cout<<*p<<endl;
cout<<&p<<endl;
cout<<(void*)p<<endl;
return 0;
}
输出:
hello
h
0x7fffd5a83448
0x400a94