I've just started to learn c and i wanted to try the strcmp function, but it somehow always gives me the result "1", if I run it. Doesn't matter what strings I type in. Since the first string is shorter than the second, i expected "-1" as a result.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;
i= strcmp(array1,array2);
printf(" %d", i);
return 0;
}
I also already tried to get rid of the i variable and just write "printf(" %d", strcmp(array1, array2)); and replacing the %d by a %u, but also not working. I've already searched the web and tried figuring it out for myself, probably just a simple mistake, would be glad if anyone could help. :)
strcmp
in libc's is almost always coded with some equivalent of the following:
int strcmp(char *s1, char *s2)
{
for(; *s1 && *s2; s1++, s2++)
{
int res = *s1-*s2;
if (res)
return res;
}
return *s1-*s2;
}
It returns the difference between the first different compared char, this ensure that the result is compliant with the two strings relation ==
<
>
.
When the strings length is different the return is the difference between the \0
string ending of the shorter one and the position corresponding char of the other string. So the the result shall reflect also the length difference.
Simply don't expect 0, 1 and -1.