简体   繁体   English

Strcmp的行为不符合预期,比较两个不相等的字符串时返回0

[英]Strcmp does not behave as expected, Returns 0 when comparing two unequal strings

I am having understanding a weird behavior of strcmp function, which will be illustrated by the following code: 我已经了解了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;
}

What I fail to understand is why the output of line 15 is 0. 0 means the two strings are equal, which is clearly not the case. 我不明白的是为什么第15行的输出为0。0表示两个字符串相等,显然不是这种情况。 What am I missing here? 我在这里想念什么?

PS I do apologize for the escape characters in the headers, but I could not get iostream to display if I removed it. PS我确实对标头中的转义字符表示歉意,但是如果删除它,我将无法显示iostream。 Though I am posting this, I will figure out how to get it right for next time. 尽管我发布了此内容,但我将找出下一次的正确处理方法。 :) :)

The problem is that p points to a string literal, therefore your attempt to modify the string literal with cin >> p; 问题是p指向字符串文字,因此您尝试使用cin >> p;修改字符串文字cin >> p; leads directly to undefined behavior. 直接导致未定义的行为。

What's most likely happening is that the compiler is treating the string literal as constant (since you're not supposed to modify it) and therefore, (at compile time) determining what the result from strcmp should be, and producing that. 最有可能发生的事情是编译器将字符串文字视为常量(因为您不应该对其进行修改),因此(在编译时)确定strcmp的结果是什么,并产生该结果。 The fact that you're modifying it at run-time is ignored, because you're not supposed to do that anyway. 您在运行时修改它的事实会被忽略,因为无论如何您都不应该这样做。

Unfortunately for compatibility many compilers support this: 不幸的是,出于兼容性考虑,许多编译器都支持此功能:

char *p = "no";

Which should fail to compile and correct one is: 哪个应该无法编译和更正的是:

const char *p = "no";

If you fix that (and you should get at least warning), you would see what is the issue with following compile errors. 如果您解决了该问题(至少应该得到警告),则将看到随后的编译错误是什么问题。

p is pointing to the first element of an array of const char . p指向const char数组的第一个元素。 Attempting to modify these values (as you do in cin >> p ) invokes undefined behaviour. 尝试修改这些值(如在cin >> p所做的那样)会调用未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM