c++面试题字符串拷贝函数示例
#include<iostream>
using namespace std;
//字符串拷贝函数
char * sCpy(char *strDest, char *strSource)
{
_ASSERT((strDest != NULL) && (strSource!=NULL));
char *d = strDest; //获取dest的当前位置
char *s = strSource; //获取source的当前位置
while ((*d++ = *s++) != '\0') //未到最后一位,作循环
{
}
*d = '\0'; //补充最后一位
return strDest;
}
int main()
{
char *strSource = "hello,world";
char *strDest = new char[strlen(strSource)+1]; //注意,strlen函数的返回长度是不包括'\0'的,所以要加1
_ASSERT(strDest != NULL);
char *strReturn = sCpy(strDest,strSource);
cout<<"形参返回值"<<strDest<<endl;
cout<<"函数返回值"<<strReturn<<endl;
//不作释放操作也应该是没问题的,主线程退出后系统会回收资源
delete strSource,strDest,strReturn;
strSource = strDest = strReturn = NULL;
return 0;
}
strcpy(str1,str2)函数能够将str2中的内容复制到str1中,为什么还需要函数返回值?应该是方便实现链式表达式,比如:
int i_length = strlen(strcpy(str1,str2));
相关文章
- 这个也算是企业招工里面比较常见的一道笔试面试题了,非常简单。个人觉得考的主要是对指针使用的熟练程度,还有对字符串类内部原理的掌握程度...2020-04-25