Implementation of strcpy function (C++)

/*   
    已知strcpy函数的原型是 char *strcpy(char *strDest, const char *strSrc);
    其中strDest是目的字符串,strSrc是源字符串
*/

#include <iostream>
using namespace std;

char* myStrcpy(char* strDest, const char* strSrc) {
    
    
	if (strDest == nullptr || strSrc == nullptr || strDest == strSrc) {
    
    
		return strDest == strSrc ? strDest : nullptr;
	}
	size_t len = strlen(strSrc);
	while (len > 0) {
    
    
		*(strDest + len) = *(strSrc + len--);
	}
	*strDest = *strSrc;
	return strDest;
}

int main() {
    
    
	char strSrc[10]{
    
     "hello" };
	char strDest[10];
	/* 返回 char * 类型是因为需要实现链式表达式,如下面这条语句 */
	cout << strlen(myStrcpy(strDest, strSrc)) << endl;
	cout << strDest << endl;
	system("pause");
	return 0;
}

If there is any infringement, please contact to delete it. If there is an error, please correct me, thank you

Guess you like

Origin blog.csdn.net/xiao_ma_nong_last/article/details/105280765