memcpy:(void * memcpy ( void * destination, const void * source, size_t num );)<string.h>
memcpy函数相较于strcpy优点是能实现各种类型数据的拷贝
代码实现:
int main() {
int arr1[5] = { 0,1,2,3,4 };
int arr2[5] = { 5,6,7,8,9 };
for (int i = 0; i < 5; i++) {
printf("%d ", arr1[i]);
}
printf("\n");
memcpy(arr1, arr2, 5 * sizeof(int));
for (int i = 0; i < 5; i++) {
printf("%d ", arr1[i]);
}
return 0;
}
运行结果:
模拟实现(部分):
void* my_memcpy(void* destination, const void* source, size_t num) {
assert(destination && source);
char* p = (char*)destination;
while (num) {
*(char*)destination = *(char*)source;
destination = (char*)destination + 1;
source = (char*)source + 1;
num--;
}
return p;
}
memmove:(void * memmove ( void * destination, const void * source, size_t num );)
相信各位在使用memcpy函数进行数组自我追加时会遇到以下情况:
int main()
{
int arr1[10] = {0,1,2,3,4,5,6,7,8,9};
memcpy(arr1+2,arr1,5*sizeof(int));
int i=0;
for(i=0;i<10;i++){
printf("%d ",arr1[i]);
}
return 0;
}
期待输出:0 1 0 1 2 3 4 7 8 9
实际输出:0 1 0 1 0 1 0 7 8 9
可以看到,memcpy内部实现只是单纯的进行地址内容的赋值操作,并没有对重叠区域进行处理。这就会导致到dst和src的地址存在重叠时,拷贝异常。
所以当面对arr1和arr2有内存重叠时用memmove更加合适
更改后代码:
int main()
{
int arr1[10] = {0,1,2,3,4,5,6,7,8,9};
memmove(arr1+2,arr1,5*sizeof(int));
int i=0;
for(i=0;i<10;i++){
printf("%d ",arr1[i]);
}
return 0;
}
输出:0 1 0 1 2 3 4 7 8 9