【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';
相关文章推荐
- C++学习笔记(一)--整形,std输出,浮点数,数组,字符串,结构,指针,循环
- C++基础教程 学习笔记(二) 数组、字符串和指针
- 数组、指针和字符串(一)------C++学习笔记
- c++学习笔记2——指向字符串的指针数组?
- C_PlusPlus学习笔记 - 5_数组、指针和字符串 (C++语言程序设计【第三版】 郑莉等,清华大学出版社)
- C++学习笔记(四)——数组和指针
- The C++ Programming Language 学习笔记 第5章 指针、数组和结构
- C++学习笔记--指针和多维数组
- C++入门笔记(四)数组、指针与字符串
- C++学习笔记(三)——对象数组的指针和对象指针的数组
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 习题2.8 随机数组的三种生成算法(补) 将bash的实现翻译成比较纯正的bash风格
- C++学习笔记(第六章 初识指针 及 指针与数组 之一)
- C/C++学习笔记18:指针数组和数组指针
- c++指针学习笔记--交换两个字符串数据收藏
- C/C++中关于地址、指针和引用变量的学习笔记(二) : 数组
- 【C语言学习笔记】数组、字符串、指针
- C/C++学习笔记:指针与数组
- C++语法笔记 – 数组 指针与字符串
- C++ Primer学习笔记2--c++中的数组和指针
- C++学习笔记 | 第三章 字符串、向量和数组 | (1)