memcpy和memmove
作者:
贺谦
,
2020-12-28 13:39:59
,
所有人可见
,
阅读 506
memcpy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *Memcpy(void *dst, const void *src, size_t size)
{
char *psrc;
char *pdst;
if(NULL == dst || NULL == src)
{
return NULL;
}
if((src < dst) && (char *)src + size > (char *)dst) // 自后向前拷贝
{
psrc = (char *)src + size - 1;
pdst = (char *)dst + size - 1;
while(size --)
{
*pdst-- = *psrc--;
}
}
else
{
psrc = (char *)src;
pdst = (char *)dst;
while(size--)
{
*pdst++ = *psrc++;
}
}
return dst;
}
int main(int argc, char *argv[])
{
char buf[100] = "abcdefghijk";
//memcpy(buf+2, buf, 5);
Memcpy(buf+2, buf, 5);
printf("%s\n", buf);
}
memmove
#include <stddef.h>
void* Memmove(void* dst, const void* src, size_t cnt)
{
char* dstp = dst;
const char* srcp = src;
if (src < dst)
{
dstp += cnt;
srcp += cnt;
while (cnt --)
{
*-- dstp = *-- srcp;
}
}
else
{
while (cnt --)
{
*dstp ++ = *srcp ++;
}
}
return dstp;
}
int main()
{
char str[] = "memmove can be very useful";
Memmove(str + 20, str + 15, 11);
printf("%s\n", str);
return 0;
}
谢谢楼主,代码写得很清楚。