#include<iostream>
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 << "一样" << endl;
}
else
{
cout << "不一样" << endl;
}
if (str3 == str4)
{
cout << "一样" << endl;
}
else
{
cout << "不一样" << endl;
}
return 0;
}
第一个输出答案:"不一样。 "str1 和 str2 是两个字符串数组,我们会为它们分配两个长度为12个字节的空间,并把"hello world"的内容分别复制到数组中去。这是两个初始地址不同的数组,所以 str1 和 str2 的值也不一样。
第二个输出答案:"一样"。 str3 和 str4 是两个指针,我们无须为它们分配内存以存储字符串的内容,而只需要把它们指向"hello world"在内存中的地址就可以了。由于"hello world"是常量字符串,它在内存中只有一个拷贝,所以str3 和 str4指向的是同一个地址。所以它们是一样的。