字符串拷贝

#include 
#include 
#include 
#include 
using namespace std;
char *my_memcpy(char *dst, const char* src, int cnt)
{
    assert(dst != nullptr && src != nullptr);
    char *ret = dst;
    if (dst >= src && dst <= src+cnt-1) //内存重叠,从高地址开始复制
    {
        cout << "test1" << endl;
        dst = dst+cnt-1;
        src = src+cnt-1;
        while (cnt--)
            *dst-- = *src--;
    }
    else    //正常情况,从低地址开始复制
    {
        cout << "test2" << endl;
        while (cnt--)
            *dst++ = *src++;
    }
    return ret;
}
char *my_memcpy1(char *dst, const char* src, int cnt)
{
    assert(dst != nullptr && src != nullptr);
    char* res = dst;
    if(dst > src && dst <= src + cnt - 1){
        cout << "test1" << endl;
        for(int i = cnt - 1; i >= 0; --i){
            dst[i] = src[i];
        }
    }
    else{
        cout << "test2" << endl;
        for(int i = 0; i < cnt; ++i){
            dst[i] = src[i];
        }
    }
    return res;
}
int main(void)
{
    char src[15] = "i love you mom";
    char dest[15] = "\0";
    my_memcpy1(dest, src, 14);
    printf("dest = %s\n", dest);
    return 0;
}


 

你可能感兴趣的:(面试)