0.1版本
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(char *dst, char *src,int count)
{
assert(dst);
assert(src);
assert(count > 0);
while (count--)
{
*dst++ = *src++;
}
}
int main()
{
char msg[256] = "hello world";
char buf[256] = {0};
memmove(buf, msg, strlen(msg));
printf("%s", buf);
system("pause");
return 0;
}
0.1版本,基本实现了函数的功能,如果其他人要使用,很不方便,假如现将count结构体对象,移到另外一个地方,必须把结构体指针强转成(char*),才能正常运行。这样会很麻烦,如何解决这个问题呢,用一种特别的指针,任意类型都可以对它进行赋值,就是void*.
0.2版本:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(void *dst, void *src, int count)
{
assert(dst);
assert(src);
assert(count > 0);
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
}
int main()
{
char msg[256] = "hello world";
char buf[256] = {0};
memmove(buf, msg, strlen(msg));
printf("%s", buf);
system("pause");
return 0;
}
当然你会问,这也是强转啊,没错。不过这一次强制转换指针却将使用者的代码,转移到库的代码里,我么可以将memmove理解为库,而将test(测试)理解为使用者。这样就可以达到一劳永逸的效果。
0.3版本:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(void *dst, void *src, int count)
{
assert(dst);
assert(src);
assert(count > 0);
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
}
int main()
{
char msg[255] = "hello world";
memmove(msg + 1, msg, strlen(msg) + 1);
printf("%s", msg);
system("pause");
return 0;
}
测试用例会出现以下结果,这是为什么呢?有的人会说从高地址拷贝,不过发生了重叠,原因出在源地址区间和⽬的地址区间有重叠的地⽅。所以最完美的解决⽅案还是判断源地址和⽬的地址的⼤⼩,才决定到底是从⾼地址开始 拷贝还是低地址开始拷贝。
第一种情况:
第二种情况:
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(void *dst, void *src, int count)
{
assert(dst);
assert(src);
assert(count > 0);
int ret = dst;
if (dst <= src || (char*)src >= (char*)dst + 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;
}
int main()
{
char msg[256] = "hello world";
memmove(msg + 1, msg, strlen(msg) + 1);
printf("%s", msg);
system("pause");
return 0;
}
结果如下: