不使用字符串处理的库函数,实现strcpy

#include 
#include 

int mstrlen(const char* p)
{
    if(!p || *p == '\0')
    {
        return 0;
    }else{
        return mstrlen(p+1)+1;  
    }
}

char* mmemcpy(void *dest, const void *src, unsigned int len)
{
    /*需要考虑到dest和src在堆区存在重叠的情况*/
    void *ret = dest;
    if(dest && src) 
    {
        if((dest < src) || (((char *)dest > (char *)src)+len)){
            while(len--){
                *(char *)dest = *(char *)src;   
                dest = (char *)dest + 1;
                src = (char *)src + 1;
            }
        }else{
            dest = (char *)dest + len -1;
            src = (char *)src + len -1;
            while(len--){
                *(char *)dest = *(char *)src;   
                dest = (char *)dest - 1;
                src = (char *)src - 1;
            }
        }   
    }

    return ret;
}

char* mstrcpy(char *dest, const char *src)
{
    char *ret = dest;
    if(dest && src)
    {
        mmemcpy(dest, src, mstrlen(src)+1); 
    }

    return ret;
}

int main(void)
{
    const char *src = "hello";
    char *dest = malloc(sizeof(char)*6);

    mstrcpy(dest, src);

    printf("%s\n", dest);

    return 0;
}

你可能感兴趣的:(C语言学习)