1.模拟实现memcpy
#include<stdio.h>
#include<assert.h>
void* my_memcpy(void* dest,void* src,int count)
{
char* pdest=(char*) dest;//必须要把目标数组跟原数组强制转化为char*指针,因为count需要一个一个字节拷贝。
char* psrc =(char*) src;
assert(dest!=NULL);
assert(src!=NULL);
while(count)
{
* pdest++=* psrc++;
count--;
}
return dest;
}
int main()
{
int arr[10];
int str[]={1,2,3,4,5,6,7,8,9,0};
my_memcpy(arr,str,8*sizeof(int));
system("pause");
return 0;
}
2.模拟实现memmove
#include<stdio.h>
#include<assert.h>
void* my_memmove(void* dest,void* src,int count)
{
char* pdest=(char*) dest;
char* psrc =(char*) src;
assert(dest!=NULL);
assert(src!=NULL);
if((pdest>=psrc)&&(pdest<=psrc+count))
{
while(count)//从后向前拷贝
{
*(pdest+count-1)=*(psrc+count-1);
count--;
}
}
else
{
while(count)//从前向后拷贝
{
* pdest++=* psrc++;
count--;
}
}
}
int main()
{
int str[]={1,2,3,4,5,6,7,8,9,0};
my_memmove(str+2,str,2*sizeof(int));
system("pause");
return 0;
}
#include<stdio.h>
#include<assert.h>
void* my_memcpy(void* dest,void* src,int count)
{
char* pdest=(char*) dest;//必须要把目标数组跟原数组强制转化为char*指针,因为count需要一个一个字节拷贝。
char* psrc =(char*) src;
assert(dest!=NULL);
assert(src!=NULL);
while(count)
{
* pdest++=* psrc++;
count--;
}
return dest;
}
int main()
{
int arr[10];
int str[]={1,2,3,4,5,6,7,8,9,0};
my_memcpy(arr,str,8*sizeof(int));
system("pause");
return 0;
}
2.模拟实现memmove
#include<stdio.h>
#include<assert.h>
void* my_memmove(void* dest,void* src,int count)
{
char* pdest=(char*) dest;
char* psrc =(char*) src;
assert(dest!=NULL);
assert(src!=NULL);
if((pdest>=psrc)&&(pdest<=psrc+count))
{
while(count)//从后向前拷贝
{
*(pdest+count-1)=*(psrc+count-1);
count--;
}
}
else
{
while(count)//从前向后拷贝
{
* pdest++=* psrc++;
count--;
}
}
}
int main()
{
int str[]={1,2,3,4,5,6,7,8,9,0};
my_memmove(str+2,str,2*sizeof(int));
system("pause");
return 0;
}