代码
int Test() {
// Test1
char str1[] = "hello world";
char str2[] = "hello world";
if (str1 == str2) cout << "str1 equal str2" << endl;
else cout << "str1 is not equal to str2" << endl;
char *pstr1 = "hello world";
char *pstr2 = "hello world";
if (pstr1 == pstr2) cout << "pstr1 equal to pstr2" << endl;
else cout << "pstr1 is not equal to str2" << endl;
// Test2
char str3[12];
str3 = "hello world"; //error
char *pstr3;
pstr3 = "hello world";
// Test3
char str4[] = "hello world";
str4[0] = 'x';
cout << str4 << endl;
char *pstr4 = "hello world";
pstr4[0] = 'x'; //运行error
cout << pstr4 << endl;
return 0;
}
Test1结果:
str1 is not equal to str2
pstr1 equal pstr2
分析 :
在C++中,常量字符串存储于一块特殊的存储区且仅有一份拷贝,当为pstr1和pstr2赋值相同的字符串常量时候,他们实际上指向相同的内存地址。
但用常量初始化数组,情况有所不同。对于数组初始化来说,字符串常量相当于构造函数中的初始化列表,当初始化数组时,会为数组分配相应长度的空间,并把字符串常量复制到数组中去。str1和str2的初始地址不同,因此它们的值也是不同的。
两者类似浅拷贝与深拷贝。
Test2结果:
为str3赋值时候会报错,pstr3却不会。
分析:
因为str3是数组名,是指针常量,不能修改。
pstr3是普通指针,赋值时,指向内存中的字符串常量的地址。
Test3结果:
运行期间报错:段错误
分析:
str4是容量大小为6的首地址,str4[0]表示容量中第1个元素,可以修改。
pstr4是指针,指向常量字符串”hello world”(位于常量储存区),不可修改