【发布时间】: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 >> p;- 我们又来了。 -
顺便说一句,GCC 提供了一个非常有用的警告:
warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] -
@chris 如果 OP 使用 gcc 编译它
-
如果你使用 C++,为什么不直接使用
std::string?
标签: c++ cstring strcmp char-pointer