1

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. :)

  • 5
    It doesn't just compare the lengths. It does a character-by-character comparison, and `k` comes before `n`. – Cody Gray - on strike Jul 08 '17 at 19:46
  • 2
    `strcmp(s1, s2)` should not return 1, 0 or -1, but an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively. You must compare result to be `==0`, `<0` or `>0`. – Frankie_C Jul 08 '17 at 19:47
  • If you want to compare string lengths do so directly: `if (strlen(a) < strlen(b)) puts("-1");` – pmg Jul 08 '17 at 19:51

2 Answers2

0

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.

Frankie_C
  • 4,764
  • 1
  • 13
  • 30
-1

Look at this little program, which is structured kind of like your own program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  char array1[]="a";
  char array2[]="b";
  int i;

  i = strcmp(array1,array2);

  printf(" %d\n", i);

  return 0;
}

Compile and run that, and it returns a negative integer. (It returns -1 on my gcc box.)

That's because "the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2."

Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185
  • Okay, so I just misunderstood the function itself. Thank you so much! –  Jul 08 '17 at 19:55