Coder strcmp en C

Bonsoir a tous.

Mon probleme est que je tente de recoder un strcmp en C et que j’ai un petit segFault qui est venu se glisser la dedans…

Je vous colle mon code afin que vous puissiez m’aider. (pas juste une reponse brute si possible accompagner d’explication merci :wink: )

int     my_strcmp(char *s1, char *s2)
{
  int   i;
  int   j;

  i = 0;
  j = 0;
  while (s1[i] || s2[j])
    {
      if (s1[i] != s2[j])
        {
          if (s1[i] > s2[j])
            return (1);
          if (s1[i] < s2[j])
            return (-1);
        }
      if (s1[i] != '\0')
        i++;
      if (s2[j] != '\0')
        j++;
    }
  return (0);
}

int     main()
{
  char  str[5];
  char  str2[5];

  str[0] = 'o';
  str[1] = 'l';
  str[2] = 'd';
  str[3] = 'n';
  str[4] = '\0';

  str2[0] = 'f';
  str2[1] = 'o';
  str2[2] = 'l';
  str2[3] = 'd';
  str2[4] = '\0';
  res = my_strcmp(str, str2);
  my_putstr(res);
  write(1, "\n", 1);
}

Merci d’avance pour toute vos reponse.

Salut,
j’ai voulu tester ton code et résultat, ca marche bien chez moi.
J’ai juste rajouté les librairies, la déclaration de res et utilisé des printf.

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

int my_strcmp(char *s1, char *s2)
{
 int i;
 int j;

 i = 0;
 j = 0;
 while (s1[i] || s2[j])
 {
 if (s1[i] != s2[j])
 {
 if (s1[i] > s2[j])
 return (1);
 if (s1[i] < s2[j])
 return (-1);
 }
 if (s1[i] != '\0')
 i++;
 if (s2[j] != '\0')
 j++;
 }
 return (0);
}

int main()
{
 char str[5] = {'t','e','s','t','\0'};
 char str2[5] = {'t','e','s','t','\0'};
 char str3[5] = {'s','e','s','t','\0'};
 int res;

 /*str[0] = 'o';
 str[1] = 'l';
 str[2] = 'd';
 str[3] = 'n';
 str[4] = '\0';

 str2[0] = 'f';
 str2[1] = 'o';
 str2[2] = 'l';
 str2[3] = 'd';
 str2[4] = '\0';*/
 res = my_strcmp(str, str2);
 printf("Resultat1 = %d\n", res);
 res = my_strcmp(str, str3);
 printf("Resutat2 = %d\n", res);
 res = my_strcmp(str3, str);
 printf("Resutat3 = %d\n", res);
 //my_putstr(res);
 //write(1, "\n", 1);
 
 return(1);
}

EDIT :
Par contre, étant débutant en c, je fais plutot (ca à l’air de marcher et je suis plus à l’aise avec cette écriture) :

int my_strcmp(char *s1, char *s2)
{
 int i;
 i = 0;
 
 while (s1[i] != '\0' && s2[i] != '\0')
 {
 if (s1[i] != s2[i])
 {
 if (s1[i] > s2[i])
 return (1);
 if (s1[i] < s2[i])
 return (-1);
 }
 i++;
 }
 return (0);
}

Edité le 12/10/2010 à 19:30

Okay, merci beaucoup :wink: