蘭雅sRGB преди 4 месеца
родител
ревизия
b204387f01
променени са 1 файла, в които са добавени 37 реда и са изтрити 0 реда
  1. 37 0
      memchr_strlen_diy.c

+ 37 - 0
memchr_strlen_diy.c

@@ -0,0 +1,37 @@
+#include <stdio.h>
+size_t strlen_diy(const char *s) {
+  const char *a = s;
+  for (; *s; s++)
+    ;
+  return s - a;
+}
+
+void *memchr_diy(const void *src, int c, size_t n) {
+  const unsigned char *s = src;
+  c = (unsigned char)c;
+
+  for (; n && *s != c; s++, n--)
+    ;
+
+  return n ? (void *)s : 0;
+}
+
+size_t strnlen_diy(const char *s, size_t n) {
+  const char *p = memchr_diy(s, 0, n);
+  return p ? p - s : n;
+}
+
+int main() {
+  char str[] =
+      "Locate character in block of memory\n"
+      "Searches within the first num bytes of the block of memory pointed by "
+      "ptr for the first occurrence of value (interpreted as an unsigned "
+      "char), and returns a pointer to it.";
+  puts(memchr_diy(str, '(', strlen_diy(str)));
+
+  int len = strnlen_diy(str, 512);
+
+  printf("len: %d\n", len);
+
+  return 0;
+}