strcpy函数;memcpy函数;memmove函数

strcpy函数实现:

char* strcpy(char* des,const char* source)
{
  char* r=des;
  assert((des != NULL) && (source != NULL));
    while((*des++ = *source++)!='\0')
      ; //do nothing.
    return r;
}

memcpy函数实现:

void* memcpy(void* dst,const void*src,size_t count)
{
    void*ret=dst;
    while(count--){
        *(char *)dst = *(char *)src;
        dst = (char *)dst+1;
        src = (char *)src+1;
    }
    return ret;
}

考虑重叠情况的话,这样实现好点:

char *my_memcpy(char *dst, const char* src, int cnt)
{
    assert(dst != NULL && src != NULL);
    char *ret = dst; 

    if (dst >= src && dst <= src+cnt-1) //des在右的内存重叠,从高地址开始复制
    {
        dst = dst+cnt-1;
        src = src+cnt-1;
        while (cnt--)
            *dst-- = *src--;
    }
    else    //正常情况,从低地址开始复制
    {
        while (cnt--)
            *dst++ = *src++;
    }
    
    return ret;
}

memmove函数实现:

void *mymemmove(void *dest, const void *src, size_t n)
{
    char temp[n];
    int i;
    char *d = dest;
    const char *s = src;

    for (i = 0; i < n; i++) 
        temp[i] = s[i];
    for (i = 0; i < n; i++) 
        d[i] = temp[i];

    return dest;
}

 

posted on 2017-12-11 13:24  willaty  阅读(223)  评论(0编辑  收藏  举报

导航