void* memcpy(void *dest , const void* src , size_t count)其中dest是目的指针,src是源指针。不调用c++/c的memcpy库函数,请编写memcpy。
方案一:没有考虑重复,不太好
void *mymemcpy(void *dst,const void *src,size_t num)
{
assert((dst!=NULL)&&(src!=NULL));
//assert(des>=src+num||src>dst+num);
byte * psrc = (byte *)src;//byte 既为unsigned char类型
byte * pdst = (byte *)dst;
while(num-->0)*pdst++ = *psrc++;
return dst;
}
方案二:考虑重复情况
代码中,无论谁在前在后,如果保证调用函数后,两个字符串都能用,就必须加上两个重复判断!
void* memcpy(void *dst, const void *src, size_t count)
{
//安全检查
assert( (dst != NULL) && (src != NULL) );
unsigned char *pdst = (unsigned char *)dst;
const unsigned char *psrc = (const unsigned char *)src;
//防止内存重复
assert(!(psrc<=pdst && pdst<psrc+count));
assert(!(pdst<=psrc && psrc<pdst+count));
while(count--)
{
*pdst = *psrc;
pdst++;
psrc++;
}
return dst;
}
方案三:如果有重复,也会进行复制,但要注意,传入的指针是void类型的,一定要转换成char *类型!
void * mymemcpy(void *dest, const void *src, size_t count)
{
if (dest == NULL || src == NULL)
return NULL;
char *pdest = static_cast <char*>(dest);
const char *psrc = static_cast <const char*>(psrc);
int n = count;
if (pdest > psrc && pdest < psrc+count)
{
for (size_t i=n-1; i != -1; --i)
{
pdest[i] = psrc[i];
}
}
else
{
for (size_t i= 0; i < n; i++)
{
pdest[i] = psrc[i];
}
}
return dest;
}
void * my_memcpy(void *dst,const void *src,unsigned int count)
{
assert(dst);
assert(src);
void * ret = dst;
if (dst <= src || (char *)dst >= ((char *)src + count))//源地址和目的地址不重叠,低字节向高字节拷贝
{
while(count--)
{
*(char *)dst = *(char *)src;
dst = (char *)dst + 1;
src = (char *)src + 1;
}
}
else //源地址和目的地址重叠,高字节向低字节拷贝
{
dst = (char *)dst + count - 1;
src = (char *)src + count - 1;
while(count--)
{
*(char *)dst = *(char *)src;
dst = (char *)dst - 1;
src = (char *)src - 1;
}
}
return ret;
}