实现memcpy函数

2022-12-26 15:39:00 浏览数 (1)

好未来二面难点

代码语言:javascript复制
//如果不考虑地址重叠
void *memcpy(void *dest, const void *src, size_t count){
    const char *s=src;
    char *temp=dest;

    while(count){
        *temp  =*src  ;
    }
    return dest;
}

//如果dest和src有重叠,考虑从高位向低位复制,保证正确复制,不考虑src是否被改变
void *memcpy(void *dest, const void *src, size_t count)
{
    char *d;
    const char *s;

    if (dest > (src size)) || (dest < src))
    {
        d = dest;
        s = src;
        while (count--)
            *d   = *s  ;        
    }
    else /* overlap */
    {
        d = (char *)(dest   count - 1); /* offset of pointer is from 0 */
        s = (char *)(src   count -1);
        while (count --)
            *d-- = *s--;
    }

    return dest;
}

0 人点赞