How does strchr implementation work

前端 未结 4 934
梦毁少年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:40

    The Function Return Value should be a Constant Pointer to a Character:

    strchr accepts a const char* and should return const char* also. You are returning a non constant which is potentially dangerous since the return value points into the input character array (the caller might be expecting the constant argument to remain constant, but it is modifiable if any part of it is returned as as a char * pointer).

    The Function return Value should be NULL if No matching Character is Found:

    Also strchr is supposed to return NULL if the sought character is not found. If it returns non-NULL when the character is not found, or s in this case, the caller (if he thinks the behavior is the same as strchr) might assume that the first character in the result actually matches (without the NULL return value there is no way to tell whether there was a match or not).

    (I'm not sure if that is what you intended to do.)

    Here is an Example of a Function that Does This:

    I wrote and ran several tests on this function; I added a few really obvious sanity checks to avoid potential crashes:

    const char *mystrchr1(const char *s, int c) {
        if (s == NULL) {
            return NULL;
        }
        if ((c > 255) || (c < 0)) {
            return NULL;
        }
        int s_len;
        int i;
        s_len = strlen(s);
        for (i = 0; i < s_len; i++) {
            if ((char) c == s[i]) {
                return (const char*) &s[i];
            }
        }
        return NULL;
    }
    

提交回复
热议问题