【问题描述】:
模拟实现strcpy,完成将字符串str2拷贝到字符串atr1中。
【问题要点】:
1、源字符串必须以’\0’结束,拷贝完成后,也必须以’\0’为结束,在程序中使用语句dest[i] = ‘\0’;来完成。
2、目标空间必须足够大,以确保能够存放源字符串。
3、使用assert断言,排除掉指针为空的情况,增加代码健壮性。
【实现代码】
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//#include<string.h>
char Strcpy(char* dest, const char* src) {
assert(dest != NULL);
assert(src != NULL);
int i = 0;
for (; src[i] != '\0'; ++i) {
dest[i] = src[i];
}
dest[i] = '\0';//结束符也要拷贝
}
int main() {
char str1[1024] = "abcd";
char str2[] = "haha";
Strcpy(str1, str2);
printf("%s\n", str1);
system("pause");
return 0;
}
【运行结果】