C/C++指针与C-风格字符串

我们知道:

  • 初始化字符串数组时,使用=运算符
  • 后面处理时,可使用strcpy()strncpy()

另外说明一下,因为VS过于智能,strcpy不能使用,我才在第一行加上了#pragma warning(disable : 4996) ,这才可以使用。

看一段程序

#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来分配刚好足够存储该字符串的空间。
发布了131 篇原创文章 · 获赞 81 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_43469047/article/details/102173867