void * memcpy ( void * destination , const void * source , sizt_t num );
将整型拷贝过去
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
//将arr1中的1 2 3 4 5,拷贝到arr2中
memcpy(arr2, arr1, 5 * sizeof(int));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d\n", arr2[i]);
}
return 0;
}
将字符型拷贝过去:
#include
int main()
{
char arr1[10] = { "hello"};
char arr2[10] = { 0 };
//将arr1中的hello,拷贝到arr2中
memcpy(arr2, arr1, 5);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%\c\n", arr2[i]);
}
return 0;
}
模拟实现:
void* my_memcpy(void* dest,void*src,size_t num)
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest+1;
src = (char*)src + 1;
}
}
#include
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
//将arr1中的1 2 3 4 5,拷贝到arr2中
my_memcpy(arr2, arr1, 5 * sizeof(int));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d\n", arr2[i]);
}
return 0;
}
对于重叠的内存,无法进行*得交给memmove处理
#include
void* my_memcpy(void* dest, void* src, size_t num)
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
my_memcpy(arr1 + 2, arr1, 5 * sizeof(int));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
void * memmove ( void * destination , const void * source , size_t num );
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
memmove(arr1 + 2, arr1, 5 * sizeof(int));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
模拟实现:
#include
void* my_memmove(void* dst, void* src, size_t count)
{
void* ret = dst;
if (dst <= src || (char*)dst >= ((char*)src + 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()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr1 + 2, arr1, 5 * sizeof(int));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
C语言规定:
momcpy 拷贝的就是不重复的内存
memmove 拷贝的就是重复的内存
void * memset ( void * ptr , int value , size_t num );
memset是用来设置内存的,将内存的值以字节为单位设置成想要的内容
int main()
{
char arr[10] = "hello 123";
memset(arr, 'x', 5);
//memset在设置的时候是以字节为单位来设置的
printf("%s\n", arr);
return 0;
}
int memcmp ( const void * ptr1,const void * ptr2,szie_t num );
比较ptr1和ptr2指针指向的位置开始,向后的num个字节
#include
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[] = { 1,2,3,4,8 };
int ret = memcmp(arr1, arr2, 16);
printf("%d\n", ret);
return 0;
}