库函数学习(1):简单实现strcpy

来源:互联网 发布:必向东java 编辑:程序博客网 时间:2024/06/06 03:44

这里先附上我的实现以及测试代码。

该实现是经典实现,网络与库函数源码都能找到。

#include <stdio.h>#include <string.h>//#define NDEBUG#include <assert.h>#ifndef NULL  //防止NULL没有定义,一般NULL不会没有定义,但作为库函数还是严谨点好。 #define NULL (void *)0#endifchar *mystrcpy(char *dest, const char *src){     assert(dest != NULL && src != NULL);     //断言:在库函数实现中并没有空指针判断。如果你是做面试题请写上,如果你是做项目,请结合项目需求,平衡性能与安全。     char *cp = dest; //保存返回地址,这个很重要    while ((*dest++ = *src++) != '\0') //最核心的语句,慢慢体会吧,库函数中还有更厉害的实现,不过理解这个已经够了。 ;     return cp;}int main(void){     char hello[]="hello world!";    char test[]="hello boy!";     char dest[32] = {0};    mystrcpy(dest, hello);     printf("mystrcpy dest: %s\n", dest);    strcpy(dest, test);     printf("strcpy dest: %s\n", dest);    return 0;}


0 0
原创粉丝点击