您的位置:首页 > 编程语言 > C语言/C++

【C++学习笔记】数组和指针再C-风格字符串的演示

2017-04-03 15:08 615 查看
#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 << ps << "\n";

cout << "Enter a kind of animal: ";
cin >> animal;
//cin >> ps;
ps = animal;
cout << ps << "!\n";
cout << "Before using strcpy():\n";
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():\n";cout << animal << " at " << (int *) animal << endl;cout << ps << " at " << (int *) ps << endl;delete [] ps;cin.get();cin.get();return 0;}

程序说明:

1、const指针,表示可以用bird来访问字符串,但是不能修改它。

const char * bird = "wren";

2、对于没有进行赋值的指针,不能使用cout和cin

// cout << ps << "\n";

3、一般来说,如果给cout提供一个指针,它将打印地址。
但是如果指针的类型为char*,则cout将显示指向的字符串。如果想显示的是字符串的地址,则必须将这种指针强制转换为另一种指针类型,如int*()
ps = animal;
cout << ps << "!\n";
cout << "Before using strcpy():\n";
cout << animal << " at " << (int *) animal << endl;
cout << ps << " at " << (int *) ps << endl;
4、获得字符串的副本(即复制对应的字符串)

(1)需要分配内存来存储该字符串,可以通过声明另一个数组或使用new来完成。

例如:

ps = new char[strlen(animal) + 1];

上述代码使用strlen()来确定字符串的长度,并将它加1来获得包含空字符串时该字符串的长度,随后使用new来分配刚好足够存储该字符串的空间。
(2)将animal赋给ps是不可行的,因为只能修改存储在ps中的地址,而不能修改地址指向的值,需要使用库函数strcpy()或strncpy();

strcpy()接受两个参数,第一个是目标地址,第二个是要复制的字符串的地址。

注意,目标地址的字节如果小于字符串的字节,则会覆盖程序正在使用的其他 strcpy(ps,animal);
strncpy()接受三个系统参数,第一个是目标地址,第二个是要复制的字符串的地址,第三个是要复制的最大字符数。

要注意的是,如果该函数在到达字符串结尾之前,目标内存已用完,则不会添加空字符串。因此,应该这样写:
strcpy(ps,animal,19);
ps[19] = '\0';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: