c++ - 为什么 const char[] 和 const char* 的比较不同?

标签 c++ c

假设我有以下代码:

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++

str3str4 指向相同的 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 == str4true 还是 false 未指定,这取决于实现,而您使用的是 true

另一方面,str1str2 是独立的数组。

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/

相关文章:

c++ - 对象中的 std::string 在 push_back 到 std::vector 期间被删除

c - 为什么这段代码会抛出段错误

c - 负移位计数左移

c++ - 多边形中的内部点

c - 关于递归函数的问题?

c++ - 为什么我的代码对于形状 "rectangle"处于无限循环中?

c++ - 没有匹配函数来调用函数模板

c++ - 引用传递以错误结束

c++ - constexpr 检查两个层次相关类型之间指针的 static_cast 是否更改指针值

c - 如何访问作为指针放入数组中的结构