1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 1000
void mstrncpy(char *s, char *t, int n);
void mstrncat(char *s, char *t, int n);
int mstrncmp(char *s, char *t, int n);
int main(int argc, char *argv[]) {
int n;
char *s, *t;
n = 5;
s = malloc(sizeof(char) * MAXLEN);
t = "hello, world!";
mstrncpy(s, t, n);
printf("mstrncpy: %s\n", s);
n = 7;
t = "may the force be with you";
mstrncat(s, t, n);
printf("mstrncat: %s\n", s);
n = 5;
t = "hello";
printf("mstrcmp: %d\n", mstrncmp(s, t, n));
free(s);
return 0;
}
void mstrncpy(char *s, char *t, int n) {
for (; n > 0 && (*s++ = *t++) != 0; n--)
;
}
void mstrncat(char *s, char *t, int n) {
for (s += strlen(s); n > 0 && (*s++ = *t++) != 0; n--)
;
}
int mstrncmp(char *s, char *t, int n) {
for (; n > 0 && *t != 0; s++, t++, n--) {
if (*s != *t)
return *s - *t;
}
return 0;
}
|