memcpy

#include 
#include 
#include 
#include 

//下标法
void*  mymemcpy(void* _Dst, void const* _Src, unsigned int  _Size) {

	if (_Dst == NULL || _Src == NULL) {
		return NULL;
	}
	char * ndest = _Dst;
	char * src = _Src;	   //指针类型转换

	for (int i = 0; i < _Size; i++) {	 //循环拷贝
		ndest[i] = src[i];
	}
	return ndest;
}

//指针法
void*  mynewmemcpy(void* _Dst, void const* _Src, unsigned int  _Size) {

	if (_Dst == NULL || _Src == NULL) {
		return NULL;
	}
	int i = 0;
	for (char *dest = _Dst, *src = _Src;i<_Size; dest++, src++,i++) {
		*dest = *src;//指针法
	}

	return 	_Dst;  //C语言注意返回
}



void main() {

	int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
	int *p = malloc(sizeof(int) * 10);
	mynewmemcpy(p, a, 40);
	//第一个是地址,被拷贝进去的内存地址
	//a用于复制的内存首地址,40长度
	for (int i = 0; i < 10; i++) {
		printf("\n%d", p[i]);
	}


	char str[1024] = "hello boygod";
	char *pstr = malloc(sizeof(char)*(strlen(str) + 1)); //分配内存,处理\0
	
	//memcpy(pstr, str, strlen(str)+1); //拷贝\0
	char *pnew = mynewmemcpy(pstr, str, strlen(str) + 1); //拷贝\0
	printf("\n%s", pstr);
	printf("\n%s", pnew);  //返回值是void *,拷贝成功的地址



	system("pause");
}

你可能感兴趣的:(memcpy)