[英]strcmp results in false when strings are equal
This is my code: 这是我的代码:
if(strcmp(pch,map[i].name)==0){
printf("Equal\n");
return 0;
}
pch
is read from a file, map[i].name
has a known size of 64. This works great for strings smaller than 64. when comparing these two strings below of size 63: 从文件中读取
pch
, map[i].name
的已知大小为64。这对于小于64的字符串非常有用。当比较以下两个大小小于63的字符串时:
file11111111111111111111111111111111111111111111111111111111111
and file11111111111111111111111111111111111111111111111111111111111
和
file11111111111111111111111111111111111111111111111111111111111
everything is peachy and the result as expected is equal, but when these two (of size 64) are compared: 一切都是桃红色的,并且预期的结果是相等的,但是当比较这两个(大小为64)时:
file111111111111111111111111111111111111111111111111111111111111
and file111111111111111111111111111111111111111111111111111111111111
和
file111111111111111111111111111111111111111111111111111111111111
the return is false. 返回是错误的。 I thought of doing:
我想到了:
if(strncmp(pch,map[i].name,64)==0){
printf("Equal\n");
return 0;
}
And it does work for strings of exact size of 64, but for strings that are smaller the result is random. 它确实适用于确切大小为64的字符串,但对于较小的字符串,结果是随机的。 What kind of quirkiness am i dealing with here?
我在这里处理什么样的古怪行为?
EDIT: this is the full code: 编辑:这是完整的代码:
char * pch;
char tempFilesNeeded[100*64+100];
strcpy(tempFilesNeeded,map[i].filesNeeded);
pch = strtok(tempFilesNeeded,",");
while (pch != NULL)
{
if(strcmp(pch,map[i].name)==0){
printf("Equal\n");
return 0;
}
pch = strtok (NULL, ",");
}
Well, if it's 好吧,如果是
char pch[64];
then you can't have 64 visible characters in there, since the last entry is needed for the termination. 那么您就不能在那里有64个可见字符,因为终止需要最后一个条目。 If you do have
"file111111111111111111111111111111111111111111111111111111111111"
in that array, it's not terminated and calling strcmp()
on it invokes undefined behavior. 如果该数组中确实有
"file111111111111111111111111111111111111111111111111111111111111"
,则它不会终止,并且在其上调用strcmp()
会调用未定义的行为。
Also, as a minor point, saying that strcmp()
returns "false" is wrong, since its return is not boolean. 另外,作为次要点,说
strcmp()
返回“ false”是错误的,因为它的返回值不是布尔值。 It returns the relation between the two first differing characters; 它返回前两个不同字符之间的关系; if no characters differ the strings are equal, then it returns zero.
如果没有字符不同,则字符串相等,则返回零。
如果一个或两个数组的确切大小为64,则您将缺少最后一个'\\ 0'字符串结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.