strcpy
// remember, always use +1 when use strcpy!!!
// see Page 14 in book: The practice of programming.
// use language to calculate size of object, i.e, buf
// never use gets(), because it may overflow. use fgets.
// always check if malloc is successfully allocated
// strlen does not count the '\0'.
char *p, buf[256];
fgets(buf, sizeof(buf), stdin);
p = malloc(strlen(buf) + 1); // always use +1.
strcpy(p, buf);
// implicitly copy the '\0' to 'to'
char* strcpy(char *to, const char *from) {
char *p = to;
while(*p++ = *from++) {}
return to;
}
// explicitly copy the '\0' to 'to'
char* strcpy(char *to, const char *from) {
char *p = to;
while(*from != '\0')
*p++ = *from++;
*p = '\0';
return to;
}