As mentioned in the comments, you need either to consistently use const char*
throughout your function or, if you are required to return a (non-const) char*
then you need to explicitly cast out the constness before returning.
But there are other problems in your code! The most serious is the fact that your second for
loop doesn't stop when it finds a match: you should return the address of the character as soon as you find it.
Second (but less serious), you really don't need two loops - you can simply merge the two and either return a pointer to the found character or, if the loop ends without finding a match, return nullptr
.
Here's a much-reduced version of the function that works:
const char* mystrChr(const char* s, char c)
{
while (*s) { // Shorthand way of writing "while (*s != '\0')"
if (*s == c) return s; // Found a match, so return current pointer!
++s;
}
return nullptr; // No match found - return signal null pointer
}
If you require your function to return a non-const char*
pointer, then you can make the explicit cast, just before returning:
char* mystrChr(const char* s, char c)
{
while (*s) {
if (*s == c) return const_cast<char*>(s); // Cast away the constness
++s;
}
return nullptr; // The cast is not required when using nullptr
}
EDIT: If, as mentioned in the comments, you want to return the address of the string's "end-marker" if a nul
character is passed as the c
argument (as, in fact, the std::strchr
function does), you can do this by modifying the return
statement after the loop:
const char* mystrChr(const char* s, char c)
{
while (*s) {
if (*s == c) return s;
++s;
}
return (c == '\0') ? s : nullptr;
}