`
kmplayer
  • 浏览: 498563 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

写个函数,实现strcpy

阅读更多
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;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics