我们知道:
- 初始化字符串数组时,使用=运算符
- 后面处理时,可使用
strcpy()
或strncpy()
另外说明一下,因为VS过于智能,strcpy不能使用,我才在第一行加上了#pragma warning(disable : 4996)
,这才可以使用。
看一段程序
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39#pragma warning(disable : 4996) // 使用指向c-风格字符串的指针 #include<iostream> #include<cstring> using namespace std; int main() { char animal[20] = "bear"; const char * bird = "wren"; char * ps; cout << animal << " and "; cout << bird << "n"; // cout << ps << "n"; // 可能显示错误,可能导致崩溃 cout << "输入一种动物: "; cin >> animal; // 如果输入字符小于20是可以的 // cin >> ps; // 致命错误,不要尝试,ps还没有指向任何一个被分配的内存块 ps = animal; cout << ps << "n"; cout << "使用 strcpy() 前:n"; cout << animal << " at " << (int *)animal << endl; // (int *)animal显示animal的地址 cout << ps << " at " << (int *)ps << endl; // 显示ps的地址 ps = new char[strlen(animal) + 1]; // 新开辟一个空间 strcpy(ps, animal); // 将animal代表的字符串复制到ps指向的目标内存 cout << "使用 strcpy() 后: n"; cout << animal << "at" << (int *)animal << endl; cout << ps << " at " << (int *)ps << endl; delete[] ps; system("pause"); return 0; }
这里我们只注意几个C++亮眼的语言特性:
- 注意,用引号扩起的字符串,其实返回的都是该字符串的地址。但是如果真的要打印出来字符串地址,必须将char * 强制穿换成 int *;ps显示为字符串“fox”,而
cout << (int *)ps
显示为该字符串的地址。 ps = new char[strlen(animal) + 1];
记得我们之前说过C++数组的动态联编。
字符串"fox"不能填满整个animal数组,因此这样做浪费了空间。上述代码使用strlen()来确定字符串的长度,加1来获得包含空字符时该字符串的长度。随后,程序使用new来分配刚好足够存储该字符串的空间。
最后
以上就是伶俐帆布鞋最近收集整理的关于C/C++指针与C-风格字符串的全部内容,更多相关C/C++指针与C-风格字符串内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复