summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--05/main.c20
-rw-r--r--05/string.h67
2 files changed, 72 insertions, 15 deletions
diff --git a/05/main.c b/05/main.c
index d16347e..6757ec7 100644
--- a/05/main.c
+++ b/05/main.c
@@ -3,7 +3,7 @@
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
-
+#include <string.h>
int compar(const void *a, const void *b) {
int i = *(int *)a;
@@ -14,20 +14,10 @@ int compar(const void *a, const void *b) {
}
int main(int argc, char **argv) {
- ldiv_t l = ldiv(1000000000007, 5937448);
- printf("%ld %ld\n",l.quot,l.rem);
- int nums[10] = {8,34,1086,3872,-123,5873,3843,1762,INT_MAX,INT_MIN};
- int i;
- for (i = 0; i < 10; ++i) nums[i] = abs(nums[i]);
- qsort(nums, 10, sizeof(int), compar);
- for (i = 0; i < 10; ++i) printf("%d ", nums[i]);
- printf("\n");
- int search = 34;
- int *p = bsearch(&search, nums, 10, sizeof(int), compar);
- if (p)
- printf("Found %d\n",*p);
- else
- printf("No match\n");
+ char buf[36];
+ memset(buf, 'a', sizeof buf);
+ strncpy(buf, "hello, world!\n",36);
+ printf("%d\n",strcmp(buf, "hello, world!\n"));
return 0;
}
diff --git a/05/string.h b/05/string.h
index e585f6b..9b59637 100644
--- a/05/string.h
+++ b/05/string.h
@@ -4,5 +4,72 @@
#include <stdc_common.h>
+void *memmove(void *s1, const void *s2, size_t n) {
+ if (s1 < s2) return memcpy(s1, s2, n); // our memcpy does a forwards copy
+ // backwards copy
+ char *p = (char*)s1 + n, *q = (char*)s2 + n;
+ while (p > s1)
+ *--p = *--q;
+ return s1;
+}
+
+char *strcpy(char *s1, const char *s2) {
+ char *p = s1 - 1, *q = s2 - 1;
+ while ((*++p = *++q));
+ return s1;
+}
+
+char *strncpy(char *s1, const char *s2, size_t n) {
+ char *p = s1 - 1, *q = s2 - 1;
+ size_t i;
+ for (i = 0; i < n; ++i)
+ if (!(*++p = *++q))
+ break;
+ for (; i < n; ++i)
+ *++p = 0;
+ return s1;
+}
+
+char *strcat(char *s1, const char *s2) {
+ return strcpy(s1 + strlen(s1), s2);
+}
+
+char *strncat(char *s1, const char *s2, size_t n) {
+ // oddly, not equivalent to strncpy(s1 + strlen(s1), s2, n)
+ char *p = s1 + strlen(s1) - 1, *q = s2 - 1;
+ size_t i;
+ for (i = 0; i < n; ++i)
+ if (!(*++p = *++q))
+ break;
+ *++p = 0;
+ return s1;
+}
+
+int memcmp(const void *s1, const void *s2, size_t n) {
+ char *p = s1, *q = s2;
+ size_t i;
+ for (i = 0; i < n; ++i, ++p, ++q) {
+ if (*p > *q)
+ return 1;
+ if (*p < *q)
+ return -1;
+ }
+ return 0;
+}
+
+int strcmp(const char *s1, const char *s2) {
+ char *p = s1, *q = s2;
+ for (; *p && *q; ++p, ++q) {
+ if (*p > *q)
+ return 1;
+ if (*p < *q)
+ return -1;
+ }
+ if (*p > *q)
+ return 1;
+ if (*p < *q)
+ return -1;
+ return 0;
+}
#endif // _STRING_H