日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

strcpy、strncpy與memcpy的區別你了解嗎?

作者:石子君 更新時間: 2022-07-12 編程語言

定義

1.memcpy函數

void *memcpy(void *destin, void *source, unsigned n);

作用:函數memcpy從source指向的對象中復制n個字符到destin指向的對象中

返回值:函數memcpy返回destin的指針。

2.strcpy函數

char strcpy(char dest, const char *src);

作用:函數strcpy把src指向的串(包括空字符)復制到dest指向的數組中,src和dest所指內存區域不可以重疊且dest必須有足夠的空間來容納src的字符串。

返回值:函數strcpy返回dest的指針。

3.strncpy函數

char *strncpy(char *destinin, char *source, int maxlen);

作用:復制字符串source中的內容(字符,數字、漢字….)到字符串destinin中,復制多少由maxlen的值決定。source和destinin所指內存區域不可以重疊且destinin必須有足夠的空間來容納source的字符長度+‘\0’。

返回值:函數strncpy返回destinin的值。

實現

看看strcpy函數的實現

char *myStrcpy(char *des,char *src){
	if(des == NULL || src == NULL){
		return NULL;
	}//先看des和src的數據是否為null
	char *bak = des;//取des地址賦bak指針
	while(*src != 0){//當src的數據(p的原始數據)不為0,繼續執行
		*des = *src;//src的數據賦值給des
		des++;
		src++;//des和src的地址++下一個
	}
	*des = '\0';//while停止,也就是到src的數據位最后一位,此時令'\0'賦des
	return bak;
}

strncpy函數的實現

char *myStrncpy(char *des,char *src,int count){
	if(des == NULL || src == NULL){
		return NULL;
	}
	char *bak = des;
	while(*src != 0 && count > 0){
		*des++ = *src++;//src的數據先賦值給des;src++;des++
		count--;
	}
	if(count > 0){
		while(count > 0){
			*des++ = '\0';
			count--;
		}
		return des;
	}
	
	*des = '\0';
	return bak;
}

memcpy函數的實現

void * myMemcpy(void *dest, void *src, unsigned count)
{
	if (dest == NULL || src == NULL)
	{
		return NULL;
	}
	char* pdest = (char*)dest;
	char* psrc = (char*)src;
	while (count--)
	{
		*pdest++ = *psrc++;
	}
	return dest;
}

區別

1、strcpy 是依據 “\0” 作為結束判斷的,如果 dest 的空間不夠,則會引起 buffer overflow。

2、memcpy用來在內存中復制數據,由于字符串是以"\0"結尾的,所以對于在數據中包含"\0"的數據只能用memcpy。(通常非字符串的數據比如結構體都會用memcpy來實現數據拷貝)

3、strncpy和memcpy很相似,只不過它在一個終止的空字符處停止。當n>strlen(src)時,給dest不夠數的空間里填充"\0“;當n<=strlen(src)時,dest是沒有結束符"\0“的。這里隱藏了一個事實,就是dest指向的內存一定會被寫n個字符。

4、strcpy只是復制字符串,但不限制復制的數量,很容易造成緩沖溢出。strncpy要安全一些。strncpy能夠選擇一段字符輸出,strcpy則不能。


總結

1、dest指向的空間要足夠拷貝;使用strcpy時,dest指向的空間要大于等于src指向的空間;使用strncpy或memcpy時,dest指向的空間要大于或等于n。

2、使用strncpy或memcpy時,n應該大于strlen(s1),或者說最好n >= strlen(s1)+1;這個1 就是最后的“\0”。

3、使用strncpy時,確保s2的最后一個字符是"\0”。

原文鏈接:https://blog.csdn.net/qq_44333320/article/details/125715798

欄目分類
最近更新