【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

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