看下面的程序:
想下输出的“b”是数组的地址还是数组的元素呢?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char b[] = "this is me";
cout<< b <<endl;
return 0;
}
结果为:this is me
为什么不是首地址而是字符串呢?
因为c++自动判断数据类型,这是对c的一种改进,不过有时候反而是障碍。例如想打印一个
char*的值到一个字符串(及该字符串的第一个字符的内存地址)。但是<<运算符已经被重载
为打印char*类型的数据为空终止字符串。解决方案是将char*转换成void*(实际上,任何程
序员希望输出为地址的指针变量都要做这一转换)。
举个例子:
#include <iostream.h>
int main()
{
char *word = "test";
cout<<" Value of word is : "<< word<<endl;
cout<<" *word is : " << *word<<endl;
cout<<static_cast< void * >( word ) <<endl;
return 0;
}
结果为:
Value of word is :test
*word is : t
0x00428048
由此可知:1.可以将字符串赋给字符指针
2.字符指的是字符串首地址
3.cout后加字符指针输出的是字符串,要输出地址必须转换