memchr_strlen_diy.c 846 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include <stdio.h>
  2. size_t strlen_diy(const char *s) {
  3. const char *a = s;
  4. for (; *s; s++)
  5. ;
  6. return s - a;
  7. }
  8. void *memchr_diy(const void *src, int c, size_t n) {
  9. const unsigned char *s = src;
  10. c = (unsigned char)c;
  11. for (; n && *s != c; s++, n--)
  12. ;
  13. return n ? (void *)s : 0;
  14. }
  15. size_t strnlen_diy(const char *s, size_t n) {
  16. const char *p = memchr_diy(s, 0, n);
  17. return p ? p - s : n;
  18. }
  19. int main() {
  20. char str[] =
  21. "Locate character in block of memory\n"
  22. "Searches within the first num bytes of the block of memory pointed by "
  23. "ptr for the first occurrence of value (interpreted as an unsigned "
  24. "char), and returns a pointer to it.";
  25. puts(memchr_diy(str, '(', strlen_diy(str)));
  26. int len = strnlen_diy(str, 512);
  27. printf("len: %d\n", len);
  28. return 0;
  29. }