目录
一、memcpy
从source的位置开始向后复制num个字节的数据到destination指向的内存位置,且遇到 ' \0 ' 不会停下来,不支持source和destination重叠
void * memcpy ( void * destination, const void * source, size_t num );
1)使用
#include <stdio.h>
#include<string.h>
int main()
{
int a[] = { 0,1,2,3,4,5,6,7,8,9 };
int b[10] = { 0 };
memcpy(b,a+2,16);
for (int i = 0; i < 10; i++)
{
printf("%d", b[i]);
}
return 0;
}
运行结果:
2)模拟
#include<stdio.h>
#include<assert.h>
void* memcpy_copy(void* dest, const void* sour, size_t num)
{
assert(sour != NULL);
for (size_t i = 0; i < num; i++)
{
*((char*)dest + i) = *((char*)sour + i);
}
return dest;
}
int main()
{
int a[] = { 0,1,2,3,4,5,6,7,8,9,10 };
int b[] = { 11,22,33,44 };
size_t k = sizeof(a) / sizeof(a[0]);
memcpy_copy(a + 2, b, 16);
for (size_t i = 0; i < k; i++)
{
printf("%d ",*(a+i));
}
return 0;
}
运行结果:
二、memmove
该函数与memcpy相似,不同的是该函数支持内存的重叠,即支持source和destination重叠
void * memmove ( void * destination, const void * source, size_t num );
1)使用
#include <stdio.h>
#include<string.h>
int main()
{
int a[] = { 0,1,2,3,4,5,6,7,8,9 };
memmove(a,a+2,16);
for (int i = 0; i < 10; i++)
{
printf("%d", a[i]);
}
return 0;
}
运行结果:
2)模拟
#include<stdio.h>
#include<string.h>
void* memmove_copy(void* dest, const void* sour, size_t num)
{
if (sour < dest && (char*)sour + num >dest)
{
for (size_t i = 1; i <= num; i++)
{
*((char*)dest + num - i) = *((char*)sour + num - i);
}
}
else
{
for (size_t i = 0; i < num; i++)
{
*((char*)dest + i) = *((char*)sour + i);
}
}
return dest;
}
void print_int(int* p, int len)//打印用的
{
for (int i = 0; i < len; i++)
{
printf("%d ", *(p + i));
}
printf("\n");
}
int main()
{
int a[10] = { 0,1,2,3,4,5,6,7,8,9 };
int b[10] = { 0,1,2,3,4,5,6,7,8,9 };
memmove_copy(a + 2, a, 16);
memmove(b + 2, b, 16);
print_int(a, 10);
print_int(b, 10);
return 0;
}
运行结果: