ccastingstrchr

return ((char *)&s[i]); What & means in this statement?


I'm new to these wanderings, sorry if it's a stupid question. but can they enlighten me what what's doing there?

char    *ft_strchr(char *s, int c)
{
    int i;

    i = 0;
    if (!s)
        return (0);
    if (c == '\0')
        return ((char *)&s[ft_strlen(s)]);  // THIS LINE
    while (s[i] != '\0')
    {
        if (s[i] == (char) c)
            return ((char *)&s[i]); // THIS LINE
        i++;
    }
    return (0);

}

I know this is being performed a cast to that variable but I had not yet come apart with this & there in the middle. and to test this function if I take it out of there... it crash.

Someone help me please???

the function is working properly it finds the first occurrence of c in the string and returns the pointer with its position. I just wanted to understand this application better.


Solution

  • Regarding why the code is written in this manner/how the function works:

    It's a requirement at least from standard C strchr that the null terminator is considered part of the string. Therefore if the user of the function requests the function to search for the null terminator, it must be handled as a special case.

    Basically you have 4 possible, different outcomes:


    Some notes regarding coding style:

    So it would seem that the function could be rewritten as:

    char* ft_strchr (char *s, int c)
    {
      if(c == '\0')
        return &s[strlen(s)];
    
      for(size_t i=0; s[i] != '\0'; i++)
      {
        if(s[i] == (char)c)
        {
          return &s[i];
        }
      } 
      return NULL;
    }