一、memcpy
1.1 使用
void * memcpy ( void * destination, const void * source, size_t num );
1.前两个参数类型都是void*,因此可以拷贝任何数据类型;
2.num参数为要拷贝的字节数;
int main()
{char arr[10] = "abcdef";char brr[20] = {'\0'};int arr_int[10] = {0,1,2,3,4,5,6,7,8,9};int brr_int[10] = {0};memcpy(brr, arr, 3);memcpy(brr_int, arr_int, 4*5); //拷贝前5个,共20字节printf("%s", brr);return 0;
}
1.2 模拟实现
void* my_memcpy(void* dest, void* src, size_t num)
{assert(dest && src);void* ret = dest;while (num--){*(char*)dest = *(char*)src;dest = (char*)dest + 1;src = (char*)src + 1;}return ret;
}
二、memmove
2.1 使用
void * memmove( void * destination, const void * source, size_t num );
int main()
{int arr_int[10] = {1,2,3,4,5,6,7,8,9,10};int brr_int[10] = {0};memmove(arr_int+2, arr_int, 20);for (int i = 0; i < 10; i++)printf("%d ",arr_int[i]); //1 2 1 2 3 4 5 8 9 10return 0;
}
2.2 模拟实现
void* my_memmove(void* dest, void* src, size_t num)
{void* ret = dest;if(dest > src){while (num--){*((char*)dest + num) = *((char*)src + num);}}else{while (num--){*(char*)dest = *(char*)src;dest = (char*)dest + 1;src = (char*)src + 1;}}return ret;
}
int main()
{int arr_int[10] = {1,2,3,4,5,6,7,8,9,10};int brr_int[10] = { 1,2,3,4,5,6,7,8,9,10 };my_memmove(arr_int, arr_int+2, 20); //从前向后拷贝my_memmove(brr_int + 2, brr_int, 20); //从后向前拷贝for (int i = 0; i < 10; i++) printf("%d ",brr_int[i]);return 0;
}
三、memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
int main()
{float arr1[] = {1.0,2.0,3.0,4.0};float arr2[] = { 1.0,3.0,4.0 };int ret1 = memcmp(arr1, arr2, 4); //0int ret2 = memcmp(arr1, arr2, 8); //-1int ret3 = memcmp(arr2,arr1, 8); //1printf("%d\n%d\n%d\n", ret1,ret2,ret3);return 0;
}
四、memset
void * memset ( void * ptr, int value, size_t num );
int main()
{int arr[10] = {0};int brr[10] = {0};memset(arr, 1, 20);//01 01 01 01 //01 00 00 00for (int i = 0; i < 5; i++){memset(brr+i, 1, 1);}return 0;
}
对于arr,对其前20个字节全部设置为1,用16进制显示为01 01 01 01(此为4个字节,存储在arr[0]中,之后类推) ;
对于brr,让brr[0]...brr[4]=1,需要改变指向brr数组的指针位置;并对其1个字节处写1;