不调用库函数实现strcpy的功能

strcpy函数的原型是char *strcpy(char *strDest, const char *strSrc);

不调用任何库函数实现strcpy的功能

 1 // realize strcpy function without any library functions
 2 #include <stdio.h>
 3 #include <assert.h>
 4 
 5 char *strcpy1(char *strDest, const char *strSrc)
 6 {
 7     assert (strDest != NULL);
 8 
 9     assert (strSrc != NULL);
10 
11     char *strDestCopy = strDest;
12 
13     while ((*strDest++ = *strSrc++) != '\0');
14 
15     return (strDestCopy);
16 }
17 
18 // test
19 int main(void)
20 {
21     char str[] = "Hello World!\n";
22     char strCpy[20];
23 
24     strcpy1 (strCpy, str);
25 
26     puts (strCpy);
27 
28     return (0);
29 }

还有一个问题,strcpy为什么要返回char *,是因为返回strDest的原始值可以使strcpy函数能够支持链式表达式,例如:

1 int nLength = strlen (strcpy (strCpy, strSrc));

又如:

1 int *str = strcpy (new char[10], strSrc);

至于为什么不返回strSrc的原始值,是因为为了保护源字符串,形参strSrc用const限定了其所指的内容,把const char *作为char *返回,类型不符,编译会报错。

原文地址:https://www.cnblogs.com/ldjhust/p/3033511.html