C 编程语言:strcmp(str1, str2) 的行为
在 C 中,我有一个字符数组:
d[20]
它被分配了值 'if' 和一个空终止字符:
d[0]='i'
d[1]='f'
d[2]='\0'
strcmp(d,"if")
的值应该为 0 吗?为什么?
我希望 strcmp
返回值 0。当我运行它时,我得到的值是 -1
In C, I have a character array:
d[20]
Which is assigned the value 'if' with a null termination character:
d[0]='i'
d[1]='f'
d[2]='\0'
Should the value of strcmp(d,"if")
be 0? Why?
I expect strcmp
to return a value of 0. When I run it, I get the value of -1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您的意思是
d[0] = 'i'; d[1] = 'f'; d[2] = '\0';
,那么是的,应该返回 0。d[2] = '/0'
将分配完全不同的东西,而你的字符串不会被 null 终止。至少不是你期望的那样 - strcmp 可能会进入杂草并开始吸泥。If you mean
d[0] = 'i'; d[1] = 'f'; d[2] = '\0';
, then yes, that should return 0.d[2] = '/0'
will assign something entirely different and your string won't be null terminated. At least not where you expect it to be - strcmp will probably head off into the weeds and start sucking mud.@everyone:“/0”拼写错误是@Mark 在编辑原始问题时引入的。原件有正确的“\0”。你的大多数答案(以及关于OP的假设)都被误导了。
@mekasperasky 以下代码正确生成
0
的值。如果你能将它与你的个人代码进行比较并找到差异,那么你可能已经解决了你自己的问题。@everyone: The '/0' typo was introduced by @Mark when he edited the original question. The original had the proper '\0'. Most of your answers (and assumptions about the OP) are misdirected.
@mekasperasky The following code correctly produces the value of
0
. If you can compare it to your personal code and find the difference, you may have solved your own problem.d[2]
应该是'\0'
,而不是'/0'
。d[2]
should be'\0'
, not'/0'
.空值由: 表示,
而不是您编写的 /0 。
The null value is indicated by:
and not /0 as you wrote.
正如其他答案所提到的,
'/0'
不是空终止符,'\0'
是。您可能认为在字符文字中指定多个字符可能会产生错误;不幸的是(至少在这种情况下)C 允许“多字符”文字字符 - 但多字符文字的确切行为是实现定义的(6.4.4.4/2“字符常量”):
因此,您的
'/0'
“字符”最终会成为某个实现定义的 int 值,该值在存储在d[2]
中时会被截断。您的编译器可能会针对“多字符”文字生成警告,但这可能还取决于您为编译器提供的确切选项。例如,我从 GCC 收到以下警告(我碰巧设置了 -Wall):
In my test with MSVC and MinGW, the value of
'/0'
is0x00002f30
,因此d[2] = '/0'
最终等同于d[2] = '0'
。As other answers have mentioned,
'/0'
is not a null termination character,'\0'
is.You might expect that specifying more than one character in a character literal might generate an error; unfortunately (at least in this case) C allows 'multi-character' literal characters - but the exact behavior of multi-character literals is implementation defined (6.4.4.4/2 "Character constants"):
So your
'/0'
'character' ends up being some implementation defined int value that gets truncated when stored ind[2]
. Your compiler might generate a warning for 'multi-character' literals, but that would probably also depend on the exact options you give the compiler.For example, I get the following warning from GCC (I happen to have -Wall set):
In my tests with MSVC and MinGW, the value of
'/0'
is0x00002f30
, sod[2] = '/0'
ends up being equivalent tod[2] = '0'
.这适用于我拥有的每个 C 编译器。我没想到会有所不同。它也适用于键盘。
这在你的 C 编译器上有效吗?
This works on every C compiler I have. I did not expect differently. It also works on Codepad.
Does this work on your C compiler?