網(wǎng)站建設(shè)和優(yōu)化排名百度熱詞搜索指數(shù)
定義
1.memcpy函數(shù)
void *memcpy(void *destin, void *source, unsigned n);
作用:函數(shù)memcpy從source指向的對象中復制n個字符到destin指向的對象中
返回值:函數(shù)memcpy返回destin的指針。
2.strcpy函數(shù)
char strcpy(char dest, const char *src);
作用:函數(shù)strcpy把src指向的串(包括空字符)復制到dest指向的數(shù)組中,src和dest所指內(nèi)存區(qū)域不可以重疊且dest必須有足夠的空間來容納src的字符串。
返回值:函數(shù)strcpy返回dest的指針。
3.strncpy函數(shù)
char *strncpy(char *destinin, char *source, int maxlen);
作用:復制字符串source中的內(nèi)容(字符,數(shù)字、漢字….)到字符串destinin中,復制多少由maxlen的值決定。source和destinin所指內(nèi)存區(qū)域不可以重疊且destinin必須有足夠的空間來容納source的字符長度+‘\0’。
返回值:函數(shù)strncpy返回destinin的值。
實現(xiàn)
看看strcpy函數(shù)的實現(xiàn)
char *myStrcpy(char *des,char *src){if(des == NULL || src == NULL){return NULL;}//先看des和src的數(shù)據(jù)是否為nullchar *bak = des;//取des地址賦bak指針while(*src != 0){//當src的數(shù)據(jù)(p的原始數(shù)據(jù))不為0,繼續(xù)執(zhí)行*des = *src;//src的數(shù)據(jù)賦值給desdes++;src++;//des和src的地址++下一個}*des = '\0';//while停止,也就是到src的數(shù)據(jù)位最后一位,此時令'\0'賦desreturn bak;
}
strncpy函數(shù)的實現(xiàn)
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的數(shù)據(jù)先賦值給des;src++;des++count--;}if(count > 0){while(count > 0){*des++ = '\0';count--;}return des;}*des = '\0';return bak;
}
memcpy函數(shù)的實現(xiàn)
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;
}
區(qū)別
1、strcpy 是依據(jù) “\0” 作為結(jié)束判斷的,如果 dest 的空間不夠,則會引起 buffer overflow。
2、memcpy用來在內(nèi)存中復制數(shù)據(jù),由于字符串是以"\0"結(jié)尾的,所以對于在數(shù)據(jù)中包含"\0"的數(shù)據(jù)只能用memcpy。(通常非字符串的數(shù)據(jù)比如結(jié)構(gòu)體都會用memcpy來實現(xiàn)數(shù)據(jù)拷貝)
3、strncpy和memcpy很相似,只不過它在一個終止的空字符處停止。當n>strlen(src)時,給dest不夠數(shù)的空間里填充"\0“;當n<=strlen(src)時,dest是沒有結(jié)束符"\0“的。這里隱藏了一個事實,就是dest指向的內(nèi)存一定會被寫n個字符。
4、strcpy只是復制字符串,但不限制復制的數(shù)量,很容易造成緩沖溢出。strncpy要安全一些。strncpy能夠選擇一段字符輸出,strcpy則不能。
總結(jié)
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”。