When I write my own strchr function, there is a part in the return step that I don't understand
I'm trying to write my own strchr function for school, but there is something I don't understand.
char *ft_strchr(const char *s, int c)
{
size_t i;
size_t len;
i = -1;
len = ft_strlen(s);
while (++i < len + 1)
{
if (s[i] == (char)c)
{
return (((void *)&((char *)s)[i]));
}
}
return (NULL);
}
I have completed the code's general structure and testing stages. But I couldn't understand the return step.
return (((void *)&((char *)s)[i]));
Can you briefly explain to me what's going on here?
Solution 1:
That line is overcomplicating things and not really best possible solution.
Let's take a closer look:
char *ft_strchr(const char *s, int c)
{
...
return (((void *)&((char *)s)[i]));
...
}
First of all, return
is not a function and therefore does not need brackets around the expression. (And there are even 2 levels of unnecessary brackets) That line is exactly the same as this one:
return (void *)&((char *)s)[i];
...
That line takes some value and casts it to void*
. Casting a pointer is normally done to interpret an address as a pointer to another type than the pointer was before. Casting to void*
is normally not needed as any pointer to a data object can automatically be converted to void*
if needed.
But look at the function return type. It is char*
, not void*
. Casting the return value to void*
does not make much sense here. Instead it should be a cast to char*
if necessary. But the value already is of type char*
. Therefore just drop that thing.
return &((char *)s)[i];
That is what you actually need. The whole point of the cast is that you have a pointer to const char
and you need a pointer to char
.
You could write it a bit more readable like this:
return (char *)&s[i];
But in the end both version will return same value with same type.
I assume with that reduced expression it is easier for you to understand what is needed in that return
statement.