【问题标题】:Strcmp does not behave as expected, Returns 0 when comparing two unequal stringsstrcmp 未按预期运行,比较两个不相等的字符串时返回 0
【发布时间】:2013-03-03 04:37:29
【问题描述】:

我正在理解 strcmp 函数的奇怪行为,这将通过以下代码进行说明:

#include <iostream> 
#include <cstring>

using namespace std;

int main()
{
    char *p = "no";

    cout << p << endl;                      //Output: no
    cout << &p << endl;                     //Output: 0x28ac64
    cout << strlen(p) << endl;              //Output: 2
    cout << strcmp(p, "no") << endl;        //Output: 0

    cin >> p;                               //Input: bo

    cout << p << endl;                      //Output: bo
    cout << &p << endl;                     //Output: 0x28ac64
    cout << strlen(p) << endl;              //Output: 2

    cout << strcmp(p, "no") << endl;        //Output: 0
    return 0;
}

我不明白的是为什么第 15 行的输出是 0。0 表示两个字符串相等,显然不是这样。我在这里想念什么?

附:我为标题中的转义字符道歉,但如果我删除它,我无法显示 iostream。虽然我发布了这个,但我会弄清楚下一次如何让它正确。 :)

【问题讨论】:

  • cin &gt;&gt; p; - 我们又来了。
  • 顺便说一句,GCC 提供了一个非常有用的警告:warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
  • @chris 如果 OP 使用 gcc 编译它
  • 如果你使用 C++,为什么不直接使用std::string

标签: c++ cstring strcmp char-pointer


【解决方案1】:

问题在于p 指向一个字符串文字,因此您尝试使用cin &gt;&gt; p; 修改字符串文字会直接导致未定义的行为。

最有可能发生的是编译器将字符串文字视为常量(因为您不应该修改它),因此(在编译时)确定 strcmp 的结果应该是什么,并产生那。您在运行时修改它的事实被忽略了,因为无论如何您都不应该这样做。

【讨论】:

    【解决方案2】:

    不幸的是,为了兼容性,许多编译器都支持这个:

    char *p = "no";
    

    应该编译失败并更正的一个是:

    const char *p = "no";
    

    如果你解决了这个问题(并且你应该至少得到警告),你会看到下面的编译错误有什么问题。

    【讨论】:

      【解决方案3】:

      p 指向const char 数组的第一个元素。尝试修改这些值(就像您在 cin &gt;&gt; p 中所做的那样)会调用未定义的行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-18
        • 2017-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多