在C++的多数表达式和 cout 中,char 数组名、char 指针以及用引号括起来的字符串常量都被解释为字符串第一个字符的地址。
下面的示例程序演示了如何使用不同形式的字符串,并通过注释指出了应尽量避免的错误使用指针的方式。
//ptrstr.cpp -- 使用不同形式的字符串
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char animal[20] = "bear"; //创建char数组animal并初始化为字符串bear
const char * bird = "wren"; //创建char指针bird并初始化为指向字符串wren,字符串"wren"实际表示的是字符串的地址
char * ps; //创建char指针,但未初始化(不建议)
cout << animal << " and "; //显示bear
cout << bird << endl; //显示bird
//cout << ps << endl; //可能显示垃圾信息或程序崩溃
cout << "Enter a kind of animal: ";
cin >> animal; //如果输入小于20个字符是可以的
//cin >> ps; //不能执行,因为ps没有指向已分配的内存空间
ps = animal; //将animal赋给ps并不会复制字符串,而只是复制地址
cout << ps << "!\n"; //显示animal当前的字符串(即用户输入的字符串)
cout << "Before using strcpy():\n";
cout << animal << " at " << (int *)animal << endl; //一般来说,如果给cout提供一个指针,它将打印地址,但如果指针类型为char *,则cout将显示指
cout << ps << " at " << (int *)ps << endl; //向的字符串。如果要显示字符串的地址,则必须将这种指针强制转换为另一种指针类型,如int *
ps = new char[strlen(animal) + 1]; //使用strlen()来确定字符串的长度,并将它+1来获得包含空字符时该字符串的长度,随后程序使用new来分配刚好足够存储该字符串的空间
strcpy(ps, animal); //将animal数组中的字符串复制到新分配的空间中,不能直接将animal赋给ps,因为这样只能修改存储在ps中的地址,从而失去程序访问新分配空间的唯一途径
cout << "After using strcpy():\n";
cout << animal << " at " << (int *)animal << endl;
cout << ps << " at " << (int *)ps << endl;
delete [] ps;
return 0;
}