C語言實現strcpy

strcpy.h:html

 

 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中,爲何還須要函數返回值應該是方便實現鏈式表達式,好比:spa

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

 

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

拓展:假如考慮dst和src內存重疊的狀況,strcpy該怎麼實現

char s[10]="hello";htm

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

//strcpy(s+1, s); //應返回hhello,但實際會報錯,由於dst與src重疊了,把'\0'覆蓋了內存

所謂重疊,就是src未處理的部分已經被dst給覆蓋了,只有一種狀況:src<=dst<=src+strlen(src)it

C函數memcpy自帶內存重疊檢測功能,下面給出memcpy的實現my_memcpy。io

複製代碼
char * strcpy(char *dst,const char *src)
{
    assert(dst != NULL && src != NULL);

    char *ret = dst;

    my_memcpy(dst, src, strlen(src)+1);

    return ret;
}
複製代碼

 

my_memcpy的實現以下:
相關文章
相關標籤/搜索