#include <stdio.h>
#include <string.h>
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
memmove(arr1+2, arr1, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
输出的结果:
memmove的模拟实现:
复制代码
void* my_memmove(void* dest, const void* src, size_t num)
{
void* ret = dest;
assert(dest && src);
if (dest < src)
{
//前 -> 后
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
//后 -> 前
*((char*)dest+num) = *((char*)src+num);
}
return ret;
}
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9 };
my_memmove(arr1, arr1 + 3, 5 * sizeof(int));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
C语言中规定:
memcpy 拷贝的就是不重叠的内存
memmove 拷贝的是重叠的内存
但在VS2022中 memcpy也可以实现重叠拷贝
三、memset函数的使用
memset是用来设置内存的,将内存中的值以字节为单位设置成想要的内容。
复制代码
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "hello world";
memset (str,'x',6);
printf(str);
return 0;
}
输出的结果:
四、memcmp函数的使用
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
• 比较从ptr1和ptr2指针指向的位置开始,向后的num个字节
• 返回值如下:
复制代码
#include <stdio.h>
#include <string.h>
int main()
{
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n = memcmp(buffer1, buffer2, sizeof(buffer1));
if (n > 0)
printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
else if (n < 0)
printf("'%s' is less than '%s'.\n", buffer1, buffer2);
else
printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
return 0;
}