在c++中常量字符串放在单独的一个内存区域,当几个指针赋值给相同的常量字符串时,他们实际上会指向相同的内存地址。但是用常量内存来初始化数组,情况却有所不同。
参考下面代码
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str1[]="hello world";
char str2[]="hello world";
char* str3="hello world";
char* str4="hello world";
if(str1==str2)
cout<<"same"<<endl;
else
cout<<"not same"<<endl;
if(str3==str4)
cout<<"same"<<endl;
else
cout<<"not same"<<endl;
system("pause");
}
输出结果:
not same
same
str1和str2是两个字符串数组,我们为他们分配了两个空间,并把“hello world”复制到数组中去,这是两个初始地址不同的数组,所以str1和str2的值也不同,所以是not same
str3和str4是两个指针,我们无须为它们分配内存来存储字符串的内容,而只需要把它们指向“hello world”在内存中的地址就可以了,由于“hello world”是常量字符串,他在内存中就一个拷贝,所以str3和str4指向的是同一个地址,结果是相同的,输出same。