基本语言细节--C语言标准库函数strcpy
1.介绍
4.注意:
原型声明:extern char *strcpy(char* dest, const char *src);
头文件:#include <string.h>
功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
返回指向dest的指针。
2.实现:
/**********************
* C语言标准库函数strcpy的一种典型的工业级的最简实现
* 返回值:目标串的地址。
* 对于出现异常的情况ANSI-C99标准并未定义,故由实现者决定返回值,通常为NULL。
* 参数:
* strDestination 目标串
* s
/*
GNU-C中的实现(节选):
*/
char
*
strcpy
(
char
*d,
const
char
*s)
{
char
*r=d;
while
((*d++=*s++));
return
r;
}
/* while((*d++=*s++)); 的解释:赋值表达式返回左操作数,所以在复制NULL后,循环停止 */
3.自己动手写的一段strcpy函数:
char * strcpy(char *pstr_destination,const char * pstr_source)
{
if((nullptr!=pstr_destination) && (nullptr!=pstr_source))
{
char *pstr_destination_copy=pstr_destination;
while((*pstr_destination++=*pstr_source++)!=‘/0’) ;
return pstr_destination_copy;
}
else
{
return nullptr;
}
}
4.注意:
链式表达式的形式如:
int iLength=strlen(strcpy(strA,strB));
若是不返回开始的字符串地址,则链式表达式失效!