1 char * strcpy (char * DEST, char * SRC) 2 {3 char * D = DEST; // back up the input parameters 4 char * s = SRC; 5 6 int COUNT = 0; 7 8 assert (DEST! = NULL & SRC! = NULL); // pointer validity check
If (src = DEST) return SRC; 11 COUNT = strlen (SRC) + 1; // calculate the SRC String Length 12 if (count <= 1) return 0; // SRC string is empty 13 if (DEST <SRC | DEST> = (SRC + count) 14 {15 while (count --) 16 {* D ++ = * s ++;} // copy 17} 18 else {19 D = DEST + count; 20 s = SRC + count; 21 While (count --) 22 {23 * d -- = * s --; // copy back and forth 24} 25} 26 return DEST; 27}
1 void memcpy(void *pDst,const void *pSrc,size_t size) 2 { 3 assert(pDst!=NULL && pSrc!=NULL); 4 if((pSrc<pDst)&&((char *)pSrc+size>pDst)) 5 { 6 char *pstrSrc=(char *)pSrc + size -1; 7 char *pstrDst=(char *)pDst +size-1; 8 while(size--) 9 *pstrDst-- = *pstrSrc;10 }11 else{12 char *pstrSrc=(char *)pSrc;13 char *pstrDst=(char *)pDst;14 while(size--){15 *pstrDst++ = *pstrSrc++;16 }17 }
Strcpy and memcpy have the following three differences.
1. The copied content is different. Strcpy can only copy strings, while memcpy can copy any content, such as character arrays, integers, struct, and classes.
2. The replication method is different. Strcpy does not need to specify the length. It ends with the string Terminator "\ 0" of the copied character, so it is prone to overflow. Memcpy decides the copy Length Based on its 3rd parameters.
3. Different purposes. Strcpy is usually used to copy strings, while memcpy is generally used to copy data of other types.
Programming Implementation of strcpy and memcpy