0

while trying to regenerate the function strrchr i get this error, can someone help me understand this part?

#include <stdio.h>

char  *ft_strrchr(const char *s, int c)
{
  int i;
  char *ptr;
  ptr = NULL;
  i = 0;
  while (*s)
  {
      if (*(s + i) == (const char)c)
      {
          ptr = ((char*)(s + i));
      }
      ++i;
  }
  return (ptr);
}

int main()
{
    const char *tx = "test a test a test";
    int a = 'a';
    char *ptr = ft_strrchr(tx,a);
    printf("%c",*ptr);

    return 0;

}

lihudi
  • 860
  • 1
  • 12
  • 21
  • 1
    `char ptr;` , do you mean `char *ptr;`? – David Ranieri Jan 22 '21 at 15:37
  • 5
    `while (*s)` is an infinite loop since `s` never changes. Presumably that means `i` grows forever and you run off the end of the string into no mans land. – Retired Ninja Jan 22 '21 at 15:42
  • 2
    Changing it to `while (*(s + i))` will fix the problem mentioned by @RetiredNinja above. Note that the real `strrchr` also allows you to search for the character `'\0'` which will always be at the end of the null-terminated source string. Your version doesn't support that currently. – Ian Abbott Jan 22 '21 at 15:59

0 Answers0