多公司的面试官在面试程序员的时候,要求应聘者写出库函数strcpy()的工作方式或者叫实现,很多人以为这个题目很简单,实则不然,别看这么一个小小的函数,它可以从三个方面来考查:(1)编程风格
(2)出错处理
(3)算法复杂度分析(用于提高性能)
最好的写法如下:
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//链式访问
char * my_strcpy(char *dest, const char *src)
{//将源字符串加const,表明其为输入参数
assert(src != NULL&&dest != NULL);//对源地址和目的地址加非0断言
char *ret = dest;
while ((*dest++ = *src++))
;
return ret;//引用返回地址,方便链式操作!!
}
int main()
{
char *p = "bit-tech";
char arr[20];
//strcpy(arr,p);
printf("%d\n", strlen(my_strcpy(arr, p)));
system("pause");
return 0;
}
同样写出strlen函数