【第四章】 复合类型---4.8.3 指针和字符串

时间:2021-07-04 11:10:41
/* programNo4.20 */
/***********************************
2017年9月29日17:11:09
Athor:xiyuan255
Course:C++
Contain:ptrstr.cpp
Reference: C++ Primer plus
知识点:
1.在cout和多数C++表达式中,char数组名、char指针以及用引号括起的字符串
常量都被解释为字符串第一个字符的地址。
为什么要这样呢?因为char是字符类型,只要知道字符串的首地址,然后依次
打印出接下来的字符,直到遇到空字符('\0')结束;这样可以缩减工作量。
2.所以在打印数组名时,其实就是打印该数组中的字符串;用双引号括起来的字符
串,其实也是把首字母的地址发给cout,然后依次打印出该字符串。
*************************************/
// ptrstr.cpp -- using pointer to strings

#include <iostream>
#include <cstring> // declare strlen(), strcpy()

int main(void)
{
using namespace std;
char animal[20] = "bear"; // animal holds bear
const char * bird = "wren"; // bird holds address
char * ps; // uninitialized

cout << animal << " and "; // display bear
cout << bird << "\n"; // display wren
// cout << ps << "\n"; // may display garbage, may cause a crash

cout << "Enter a kind of animal: ";
cin >> animal; // ok if input < 20 chars
// cin >> ps; Too horrible a blunder to try; ps doesn't
// point to allocated space

ps = animal; // set ps to point to string
cout << ps << "!\n"; // ok, same sa using animal
cout << "Before using strcpy(): \n";
cout << animal << " at " << (int *) animal << endl;
cout << ps << " at " << (int *) ps << endl;

ps = new char[strlen(animal) + 1]; // get new storage
strcpy(ps, animal); // copy string to new storage
cout << "After using strcpy(): \n";
cout << animal << " at " << (int *) animal << endl;
cout << ps << " at " << (int *) ps << endl;
delete [] ps;

return 0;
}

/**
输出结果:
bear and wren
Enter a kind of animal: fox
fox!
Before using strcpy():
fox at 0016FB84
fox at 0016FB84
After using strcpy():
fox at 0016FB84
fox at 00511990
*/