strcpy.h:

 

 1 #ifndef STRCPY_H
 2 #define STRCPY_H
 3 
 4 #include <stdio.h>
 5 
 6 char *cat_strcpy(char *dst, const char *src) {
 7     if (NULL == src || NULL == src)
 8         return NULL;
 9 
10     char *s = (char *)src, *d = dst;
11 
12     while ((*d++ = *s++) != '\0') {
13         // do nothing
14     }
15     *d = '\0';
16 
17     return dst;
18 }
19 
20 #endif

 

 

main:

 1
 2 #include "strcpy.h"
 3 
 4 
 5 void test_strcpy();
 6 
 7 int main() {
 8     test_strcpy();
 9 
10     return 0;
11 }
12 
13 
14 void test_strcpy() {
15     char *src = "test_strcpy";
16     char dest[20] = { 0 };
17     cat_strcpy(dest, src);
18 
19     printf("%s\n", dest);
20 }

 

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的实现如下:

相关文章:

  • 2022-12-23
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
猜你喜欢
  • 2021-12-15
  • 2021-10-11
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2022-12-23
相关资源
相似解决方案