- 1、先看代码
//testCopy.cpp
#include <iostream>
#include <string>
using namespace std;
//声明copy函数
char * copy(char*dest,const char*src);
int main() {
char array[20] = "hello world!";
char array1[30] = "nihao,woshi hexuefeng!";
char * array2;
array2 = copy(array1,array);
cout << "array" << array << endl;
cout << "array1" << array1 << endl;
cout << "array2" << array2 << endl;
system("pause");
return 0;
}
//copy函数的实现
char *copy(char* dest,const char* src) {
if ((dest==NULL)||(src==NULL))
{
printf("参数不能为空");
return NULL;
}
//1:char * get = dest; //保存dest初始的地址
while ((*dest++=*src++)!='\0')
{
}
//2:return get;
return dest; //这里的dest已经是while循环结束后的位置`这里写代码片`了
}
输出结果是:
1:array已经把内容复制给了数组array1
2:array2却没有正确地输出结果
- 2、原因和解决方法
见源代码注解; array2输出的内容是除掉array的大小,即12个字符之后的起始位置开始输出;
正确做法是打开源代码的1,2注解行,显示结果如下: