为什么 == 运算符不会产生与 strcmp 相同的结果?

Why is the == operator not yielding the same result as strcmp?

我创建了一个二维字符指针数组。我想用它来创建一个字典,如果变量 ent 是字典的一部分,则检索该词对应的字典条目(如果它存在)。我目前正在使用 strcmp,但这只是因为 == 运算符给我带来了困难。我不确定为什么 == 运算符没有产生预期的结果。

我怀疑这可能与指针比较有关,因为我正在比较一个指向字符串的指针和另一个指向字符串的指针,而不一定是它的内容。

#include <iostream>
#include <cstring>

int main() {
    char *dictionary[][2] {
        {"First","Monday"},
        {"Second","Tuesday"},
        {"Third","Wednesday"},
        {"Fourth","Thursday"},
        {"Fifth","Friday"},
        {"Sixth","Saturday"},
        {"Seventh","Sunday"},
        {"",""}
    };

    char ent[80] = "Sixth";

        for (int i{}; *dictionary[i][0]; i++) {
            if (!strcmp(dictionary[i][0], ent)) { 
                std::cout << "Word found: " << ent 
                          << " corresponds to: " << dictionary[i][1] 
                          << std::endl;
                return 0;
            }
        }

    std::cout << ent << " not found." << std::endl;
    return 1;
}

我想用类似的东西替换 if (!strcmp(dictionary[i][0], word)) if (word == dictionary[i][0]) 并让它产生 Word found: Sixth corresponds to Saturday

如果我不能用 == 运算符做到这一点,有没有办法通过使用指针但不依赖于 header 的函数来做到这一点?

谢谢!

在if语句的条件下

if (word == dictionary[i][0])

有字符串首字符的比较地址

在表达式中,除了极少数例外情况,例如在 sizeof 运算符中使用它们,数组会隐式转换为指向其第一个元素的指针。

例如,如果您要编写这样的 if 语句

if ( "hello" == "hello" ) { /*...*/ }

然后表达式的计算结果为 truefalse,具体取决于编译器选项,该选项指定相等的字符串文字是作为一个字符串还是作为单独的字符串在内部存储。

您可以定义字典,使其元素类型为 std::string。在这种情况下,您可以使用相等运算符 ==.

在这种情况下,您可以将 std::string 类型的对象与包含字符串的字符数组进行比较,因为字符数组将隐式转换为 std::string.[=17= 类型的临时对象]