简体   繁体   中英

How to return a pointer from a char* function

I am doing an exercise that is assigned by the Prof. The problem is: Write the function myStrChr(). The function has two parameters: a const char * s pointing to the first character in a C-style string, and a char c. Return a pointer to the first appearance of c appearing inside s and nullptr (0) if c does not appear inside s.

I have been trying, but still cannot figure out how to fix the error: " invalid conversion from const char* to char*" or "invalid conversion from char* to const char* Please show me to fix it.

char* mystrChr(const char *s, char c)
{
   size_t len{};
    for (size_t i = 0; s[i] != '\0'; i++)
        len++;
    
    char *p = s;    
    for (size_t i = 0; i < len; i++)
    {
        if (s[i] == c)
            p = &s[i];
        else
            p = nullptr; 
    }
    return p;

}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM