1. 程式人生 > >memcpy函式實現

memcpy函式實現

面試時被問到,沒寫對,尷尬。

` #include #include #include #include #include #include #include #include #include #include using namespace std;

void *my_memcpy(void *dst, const void *src, size_t len) { if(NULL == dst || NULL == src) return NULL;

void *ret = dst;

if(dst <= src || (char *)dst >= (char *)src + len)
{
	//沒有記憶體重疊,從低地址開始複製
	while(len--)
	{
		*(char *)dst = *(char *)src;
		dst = (char *)dst + 1;
		src = (char *)src + 1;
	}
}
else
{
	//有記憶體重疊,從高地址開始複製
	src = (char *)src + len - 1;
	dst = (char *)dst + len - 1;
	while(len--)
	{
		*(char *)dst = *(char *)src;
		dst = (char *)dst - 1;
		src = (char *)src - 1;
	}
}
return ret;

}

int main() { int a[100],b[100],c[100]; int n; cin>>n; for(int i=0;i<n;i++) cin>>a[i]; cout<<“kakaka”<<endl; for(int i=0;i<n;i++) cout<<a[i]<<" “; cout<<endl; cout<<“a:”<<a<<” b:"<<b<<endl; my_memcpy(b,a,sizeof(int)*n); cout<<“a:”<<a<<endl; for(int i=0;i<n;i++) cout<<b[i]<<" "; cout<<endl;

return 0;

}

`