void * memcpy ( void * destination, const void * source, size_t num );
void * memmove ( void* destination, const void * source, size_t num );
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
int main()
{
int i = 0;
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
memcpy(arr2, arr1, 20);
for (i = 0; i < 10; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
int main()
{
int i = 0;
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
memcpy(arr2, arr1+2, 20);
for (i = 0; i < 10; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
void* my_memcpy(void* destination, const void* source, size_t num)
{
void* ret = destination;
assert(destination);
assert(source);
/*
* copy from lower addresses to higher addresses
*/
while (num--)
{
*(char*)destination = *(char*)source;
destination = (char*)destination + 1;
source = (char*)source + 1;
}
return(ret);
}
int main()
{
int i = 0;
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
my_memcpy(arr2, arr1+2, 20);
for (i = 0; i < 10; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
模拟实现1的代码有一个缺陷,就是不能进行自我拷贝
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
void* my_memcpy(void* destination, const void* source, size_t num)
{
void* ret = destination;
assert(destination);
assert(source);
/*
* copy from lower addresses to higher addresses
*/
while (num--)
{
*(char*)destination = *(char*)source;
destination = (char*)destination + 1;
source = (char*)source + 1;
}
return(ret);
}
int main()
{
int i = 0;
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
my_memcpy(arr1+2, arr1, 20);
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
void* my_memmove(void* destination, const void* source, size_t num)
{
void* ret = destination;
assert(destination);
assert(source);
if (destination < source)
{
//从前向后赋值
while (num--)
{
*(char*)destination = *(char*)source;
destination = (char*)destination + 1;
source = (char*)source + 1;
}
}
//从后向前赋值
else
{
while (num--)
{
*((char*)destination+num)= *((char*)source+num);
}
}
return ret;
}
int main()
{
int i = 0;
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
my_memmove(arr1+2, arr1, 20);
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
目前在vs环境下,这两个函数基本没有区别,memcpy也可以解决内存重复的问题。别的平台可能还是会有这个问题