简体   繁体   English

Strcmp()函数未返回0

[英]Strcmp() function isn't returning 0

i was trying to compare two strings using strcmp() , and in the case they're equal the function returns -1 (meaning they are not equal) , i dont know whats wrong . 我试图使用strcmp()比较两个字符串,并且在它们相等的情况下,该函数返回-1(表示它们不相等),我不知道这是怎么回事。

int main()
{
char password[]={'6','6','6','6','6','6'};
char passmatch[6];
int i =0;
for(i ; i<6 ; i++)
{
    passmatch[i]='6';
}

printf("\n");
if(strcmp(password,passmatch)==0)
{
    printf("Strings are equal");
}
else
{
    printf("String are'nt equal");
}


return 0;

} }

In C, strings need to be null terminated in order to be used with the standard library. 在C语言中,字符串必须以null终止,以便与标准库一起使用。 Try putting a '\\0' at the end, or make a string literal in the "normal" way, eg char password[] = "666666"; 尝试在末尾添加“ \\ 0”,或以“常规”方式创建字符串文字,例如char password[] = "666666"; , then the language will automatically put \\0 at the end. ,则该语言会自动在末尾加\\0

The problem is that in C '6' (with quotes) is not the same as 6 (without quotes). 问题在于C中的'6' (带引号)与6 (不带引号)不同。 That's why this loop 这就是为什么这个循环

for(i ; i<6 ; i++) {
    passmatch[i]=6; // <<== Should be '6', not 6
}

is not assigning what you want it to assign. 未分配您要分配的内容。 If you put quotes around this 6 as well, you would get the right content, but your program would remain broken, because strcmp requires null termination. 如果也用引号引起来6 ,则将获得正确的内容,但您的程序仍将损坏,因为strcmp需要空终止。

You can fix it in two ways: 您可以通过两种方式修复它:

  • Add null termination to both C strings, either manually or by initializing with a string literal, 向两个C字符串添加空终止符,方法是手动或通过字符串文字初始化,
  • Switch to using memcmp , which takes length, and therefore does not require null termination. 切换到使用memcmp ,它需要一定的长度,因此不需要null终止。

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

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