【memcpy 】手写代码 C++

void * memcpy ( void * destination, const void * source, size_t num );

 

用法:#include <string.h>

功能:由src所指内存区域复制count个字节到dest所指内存区域。

说明:src和dest所指内存区域不能重叠,函数返回指向dest的指针。

总结

1.source和destin所指的内存区域可能重叠,但是如果source和destin所指的内存区域重叠,那么这个函数并不能够确保source所在重叠区域在拷贝之前不被覆盖。而使用memmove可以用来处理重叠区域。函数返回指向destin的指针。

2.如果目标数组destin本身已有数据,执行memcpy()后,将覆盖原有数据(最多覆盖n)。如果要追加数据,则每次执行memcpy后,要将目标数组地址增加到你要追加数据的地址。

注意:source和destin都不一定是数组,任意的可读写的空间均可。

区别

strcpy和memcpy主要有以下3方面的区别。

1、复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。

2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。

3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy

 代码实现:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
/*用法:#include <string.h>

功能:由src所指内存区域复制count个字节到dest所指内存区域。

说明:src和dest所指内存区域不能重叠,函数返回指向dest的指针。*/

void* mymemcpy(void* dst, const void* src, size_t n){
	if(dst == nullptr || src == nullptr)
		return nullptr;
	
	char* pdst;
	char* psrc;
	
	if(src >= dst || (char*) dst >= (char*) src +n-1){//地址无重叠 ,自前往后拷贝
		pdst = (char*) dst;
		psrc = (char*) src;
		
		while(n--){
			*pdst++ = *psrc++;
		}
	} 
	else{//地址有重叠,自后向前拷贝
		pdst = (char*) dst + n - 1;
		psrc = (char*) src + n - 1;
		while(n--){
			*pdst-- = * psrc--;
		}
	}
	return dst;

}

 

int main(){
	char src[100] = "1234567890";
	char dst[20];
	char dsta[101];
	
	memcpy(dst+2,src,5);
	cout<<"dst:"<<dst<<endl;
	cout<< "dst+2:"<<dst+2<<endl;
	
	memcpy(src+2, src, 5);
	cout<<src<<endl;
	cout<<src+2<<endl;
	
	memcpy(dsta+2,src,5);
	cout<<"dsta:"<<dsta<<endl;
	cout<< "dsta+2:"<<dsta+2<<endl;
	 


char *s="Golden Global View";
    char d[20]; 
    memcpy(d,s,strlen(s));
    d[strlen(s)]=0;
    printf("%s",d);
cout<<endl;

memcpy(d,s+14,4);//从第14个字符(V)开始复制,连续复制4个字符(View)
//memcpy(d,s+14*sizeof(char),4*sizeof(char));也可
d[4]='\0';
printf("%s",d);
cout<<endl;


char src1[] = "******************************";
char dest1[] = "abcdefghijlkmnopqrstuvwxyz0123as6";
printf("destinationbefore memcpy: %s\n", dest1);
memcpy(dest1,src1, strlen(src1));
printf("destinationafter memcpy: %s\n", dest1);
return 0;
}

 

参考:

http://www.cplusplus.com/reference/cstring/memcpy/

https://www.cnblogs.com/ZY-Dream/p/10052766.html

https://www.cnblogs.com/Pond-ZZC/p/11820854.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章