How does memchr() work under the hood?

后端 未结 5 1404
迷失自我
迷失自我 2020-12-31 07:59

Background: I\'m trying to create a pure D language implementation of functionality that\'s roughly equivalent to C\'s memchr but uses arrays and indices i

5条回答
  •  攒了一身酷
    2020-12-31 08:33

    Here is FreeBSD's (BSD-licensed) memchr() from memchr.c. FreeBSD's online source code browser is a good reference for time-tested, BSD-licensed code examples.

    void *
    memchr(s, c, n)
        const void *s;
        unsigned char c;
        size_t n;
    {
        if (n != 0) {
            const unsigned char *p = s;
    
            do {
                if (*p++ == c)
                    return ((void *)(p - 1));
            } while (--n != 0);
        }
        return (NULL);
    }
    

提交回复
热议问题