Write the function my_strchr(). 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 NULL (0) if c does not appear inside s.

Is there something wrong with this code? It doesn't return any output when i test it with the string "adabadoo" and char 'a'

const char * my_strchr(const char * s, char c)
{
    
    for(int i = 0; i < strlen(s); i++)
    {
        if(*s == c) return s;
        else return '\0';
        s++;
    }
}

Recommended Answers

All 5 Replies

delete line 7 and move the return between lines 9 and 10. That else statement on line 7 is causing the function to return after the virst attempt to chedk the value of *s.

delete line 7 and move the return between lines 9 and 10. That else statement on line 7 is causing the function to return after the virst attempt to chedk the value of *s.

That was what I did originally but it still doesn't return any thing =?
I test it with the code my professor gave me.

char cstr[50] = "Abadabadoo!";
cout << "my_strchr(cstr, 'a') expects adabadoo!" << endl;
cout << "  -- " << my_strchr(cstr, 'a') << endl;
const char * my_strchr(const char * s, char c)
{
    
    while(*s != '\0')
    {
        if(*s == c) 
            return s;
        ++s;
    }
    return '\0';
}

Can you explain why it is ++i and not i++ ? =?

In this code it could be either one -- just a matter of programmer preference. Use which ever one you want because the outcome will be the same. I like to use ++i because with some compilers the code might be just a couple nanoseconds faster than i++.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.