- #include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
char *myStrndup(const char *str, size_t n);
-
-
int
-
main(void)
-
{
-
char *s = "Hello world\n";
-
char *r = myStrndup(s, 5);
-
printf(r);
-
free(r);
-
-
return 0;
-
}
-
-
char *
-
myStrndup(const char *str, size_t n)
-
{
-
char *new_str;
-
-
if (str) {
-
new_str= (char *)malloc(sizeof(char)*(n+1));
-
strncpy(new_str, str, n);
-
new_str[n] = '\0';
-
} else {
-
new_str= NULL;
-
}
-
-
return new_str;
- }