int main(){
char str1[] = "hello world";
char str2[] = "hello world";
char *str3 = "hello world";
char *str4 = "hello world";
if(str1 == str2)
cout<<"str1 and str2 are same.\n"<<endl;
else
cout<<"str1 and str2 are not same.\n"<<endl;
if(str3 == str4)
cout<<"str3 and str4 are same.\n"<<endl;
else
cout<<"str3 and str4 are not same.\n"<<endl;
return 0;
}
为了节省内存,C/C++把常量字符串放到单独的一个内存区域。当几个指针赋值给相同的字符串常量时,它们实际上会指向相同的内存地址。但用常量内存初始化数组,情况却不同。str1和str2是两个字符串数组,我们会为它们分配两个长度为12个字节的空间,并把“hello world”的内容分别复制到数组里,这是两个初始地址不同的数组,因此str1和str2的值也不相同。str3和str4是两个指针,我们无须为它们分配内存以存储字符串的内容,只需把它们指向“hello world”的内存中的地址就可以了。由于“hello world”是常量字符串,它在内存中只有一个拷贝,因此str3和str4指向的地址相同。注:不能对常量字符串进行修改。——《剑指offer》