C++ 基础学习第五天
指针与字符串
#include <iostream> #include <cstring> int main(){ using namespace std; char animal[20] = "bear "; const char * bird = " wren"; char * ps; cout << animal << "and"; cout << bird << "\n"; cout << "Enter a kind of animal:"; cin >> animal; ps = animal; cout << ps << endl; cout << "Before using strcpy():" << endl; cout << animal << " at " << (int *) animal << endl; cout << ps << " at " << (int *) ps << endl; ps = new char[strlen(animal) + 1]; strcpy(ps,animal); cout << "After using strcpy():" << endl; cout << animal << " at " << (int *) animal << endl; cout << ps << " at " << (int *) ps << endl; delete [] ps; return 0; }
运行结果:
一般来说,给cout提供一个指针,它将打印地址。但如果指针类型时char *,则cout将显示指向的字符串。如果要显示字符串的地址,则必须将这种指针强制转换为另一种指针类型。(如 int *)
strcpy()函数接受两个参数,第一个是目标地址,第二个是复制的字符串的地址。
用new出来的指针不能轻易给该指针赋值,因为这样做只会修改存储在此指针中的地址,从而使程序失去访问new分配内存的唯一途径。