在C/C++库函数中,有字符串拷贝函数strcpy,
其接口函数为:char *strcpy(char *str1,char *str2);
现编程实现strcpy函数的功能。
说明:str1指向的空间内存应足够大,至少可以放下str2的内容(包括结束符)。
C代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *MyStrcpy(char *str1, const char *str2) {
char *p = str1;
if (str1 == NULL || str2 == NULL) {
printf("Error!");
exit(0);
}
while (*str2 != '\0') {
*p++ = *str2++;
}
*p = '\0';
return str1;
}
int main() {
char str1[50];
char str2[50];
printf("Please input str2:");
scanf("%s", str2);
printf("Please output str1:");
printf("%s", MyStrcpy(str1, str2));
printf("\n");
}
C运行结果: