1,常见的一道面试题目,给出一个实例.
#include <iostream>
#include <stdexcept>
using namespace std;
char* MyStrcpy(char* des, const char* src)
{
//判断是否自身拷贝
if (des == src)
return des;
//判断是否有空地址
if ((des == NULL) || (src == NULL))
return NULL;
int len_d = strlen(des);
int len_s = strlen(src);
//判断目标空间是否足够
if (len_d < len_s)
throw runtime_error("not enough space.");
while (*src)
*des++ = *src++;
*des = '\0';
return des;
}
int main()
{
char a[]="hello";
char b[]="word";
try
{
//MyStrcpy(b,a);
MyStrcpy(a,b);
cout<<a<<endl;
}catch(runtime_error& err)
{
cout<<err.what()<<endl;
}
return 0;
}