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.
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:
(normal use) if (s[i] == (char) c) return ((char *)&s[i]);
The character was found, return a pointer to the found character position. The cast from int
to char
is per the requirement of standard C strchr
- it behaves like that as well. (And thereby allows to pass stuff like EOF
.)
(normal use) return (0); }
The character was not found, return NULL.
(special case) if (!s) return (0);
The user passed a null pointer to the function, return NULL. This isn't required by standard C strchr
. Since the caller might be perfectly aware they are passing a valid pointer to the function, error checks like this just add extra bloat/branches for nothing. The recommended practice is to place them on the caller side. Naively written library functions are often cluttered with null pointer checks like this.
(special case) if (c == '\0') return ((char *)&s[ft_strlen(s)]);
The user for some reason decided to search for the null terminator. It will always be found at index strlen(s)
in the array, so therefore strlen is used for indexing and then a pointer to that location of the null terminator is returned.
Also note the subtle distinction between the caller passing something explicitly zero ('\0'
) and the caller passing an int
which upon conversion to char
becomes zero. In the latter case, the function will return NULL (not found). That's why there's no cast to char
at if (c == '\0')
.
Some notes regarding coding style:
char*
to char*
is nonsense.return (0);
is pointless.for(size_t i=0; s[i] != '\0'; i++)
.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;
}