假设我有以下代码:
const char str1[] = "asdasd";
const char str2[] = "asdasd";
const char* str3 = "dsadsa";
const char* str4 = "dsadsa";
if (str1 == str2)
{
cout << "str1 == str2" << endl;
}
if (str3 == str4)
{
cout << "str3 == str4" << endl;
}
结果是“str3 == str4”。为什么?
最佳答案
对于 C++
str3
和 str4
指向相同的 string literals ,
The compiler is allowed, but not required, to combine storage for equal or overlapping string literals. That means that identical string literals may or may not compare equal when compared by pointer.
这意味着 str3 == str4
是 true
还是 false
未指定,这取决于实现,而您使用的是 true
。
另一方面,str1
和str2
是独立的数组。
String literals can be used to initialize character arrays. If an array is initialized like
char str[] = "foo";
,str
will contain a copy of the string"foo"
.
因此 str1 == str2
保证为 false
。
关于c++ - 为什么 const char[] 和 const char* 的比较不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56712420/