[英]Why isn't strcmp() working as I though it should? c++
for some reason strcmp() isn't returning 0 as it should. 由于某些原因,strcmp()没有返回0。 Here is the code:
这是代码:
#include <iostream>
#include <ccstring>
int main()
{
char buffer[2];
buffer[0] = 'o';
char buffer2[2];
char buffer2[0] = 'o';
cout<<strcmp(buffer, buffer2);
}
Thanks! 谢谢!
C strings are zero terminated. C字符串以零结尾。
Your strings aren't. 您的琴弦不是。 This is simply undefined behaviour.
这只是未定义的行为。 Anything can happen.
什么都可能发生。
Terminated the string first before comparing. 比较之前,先终止字符串。
#include <iostream>
#include <ccstring>
int main()
{
char buffer[2];
buffer[0] = 'o';
buffer[1] = 0; <--
char buffer2[2];
buffer2[0] = 'o';
buffer2[1] = 0; <--
cout<<strcmp(buffer, buffer2);
}
Edit:(March 7, 2014) : 编辑:(2014年3月7日) :
Additional string initialization: 附加的字符串初始化:
int main()
{
//---using string literals.
char* str1 = "Hello one"; //<--this is already NULL terminated
char str2[] = "Hello two"; //<--also already NULL terminated.
//---element wise initializatin
char str3[] = {'H','e','l','l','o'}; //<--this is not NULL terminated
char str4[] = {'W','o','r','l','d', 0}; //<--Manual NULL termination
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.