How does strchr implementation work

前端 未结 4 922
梦毁少年i
梦毁少年i 2020-12-08 16:08

I tried to write my own implementation of the strchr() method.

It now looks like this:

char *mystrchr(const char *s, int c) {
    while (*s != (char)         


        
4条回答
  •  执念已碎
    2020-12-08 16:39

    The const keyword means that the parameter cannot be modified.

    You couldn't return s directly because s is declared as const char *s and the return type of the function is char *. If the compiler allowed you to do that, it would be possible to override the const restriction.

    Adding a explicit cast to char* tells the compiler that you know what you're doing (though as Eric explained, it would be better if you didn't do it).

    UPDATE: For the sake of context I'm quoting Eric's answer, since he seems to have deleted it:

    You should not be modifying s since it is a const char *.

    Instead, define a local variable that represents the result of type char * and use that in place of s in the method body.

提交回复
热议问题