C语言实现strcpy

时间:2023-03-09 09:40:31
C语言实现strcpy

strcpy.h:

 #ifndef STRCPY_H
#define STRCPY_H #include <stdio.h> char *cat_strcpy(char *dst, const char *src) {
if (NULL == src || NULL == src)
return NULL; char *s = (char *)src, *d = dst; while ((*d++ = *s++) != '\0') {
// do nothing
}
*d = '\0'; return dst;
} #endif

main:

 #include "strcpy.h"

 void test_strcpy();

 int main() {
test_strcpy(); return ;
} void test_strcpy() {
char *src = "test_strcpy";
char dest[] = { };
cat_strcpy(dest, src); printf("%s\n", dest);
}

strcpy(str1,str2)函数能够将str2中的内容复制到str1中,为什么还需要函数返回值?应该是方便实现链式表达式,比如:

int length = strlen(strcpy(str1,str2));

ref:http://www.cnblogs.com/chenyg32/p/3739564.html

拓展:假如考虑dst和src内存重叠的情况,strcpy该怎么实现

char s[10]="hello";

strcpy(s, s+1); //应返回ello,

//strcpy(s+1, s); //应返回hhello,但实际会报错,因为dst与src重叠了,把'\0'覆盖了

所谓重叠,就是src未处理的部分已经被dst给覆盖了,只有一种情况:src<=dst<=src+strlen(src)

C函数memcpy自带内存重叠检测功能,下面给出memcpy的实现my_memcpy。

C语言实现strcpy
char * strcpy(char *dst,const char *src)
{
assert(dst != NULL && src != NULL); char *ret = dst; my_memcpy(dst, src, strlen(src)+1); return ret;
}
C语言实现strcpy
my_memcpy的实现如下: