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 .
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. Try putting a '\\0' at the end, or make a string literal in the "normal" way, eg char password[] = "666666";
, then the language will automatically put \\0
at the end.
The problem is that in C '6'
(with quotes) is not the same as 6
(without quotes). 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.
You can fix it in two ways:
memcmp
, which takes length, and therefore does not require null termination.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.