Introduction to strcat and strcpy in C language

  • 2020-04-02 01:08:25
  • OfStack

Strcpy prototype declaration: extern char* strcpy(char* dest, const char* SRC);
Header file: #
The include < String. H >
Function: Copy a string that starts at the SRC address and has a NULL terminator into the address space that starts with dest
Description: The memory area indicated by SRC and dest must not overlap and dest must have enough space to hold the SRC string.
Returns a pointer to dest.
Function implementation:



 char *strcpy(char *strDestination,const char *strSource)
 {
   assert(strDestination!=NULL && strSource!=NULL);
   char *strD=strDestination;
   while ((*strD++=*strSource++)!='0');
   return strDestination;
 }

 
 char* strcpy(char *d, const char *s)
 {
   char *r=d;
   while((*d++=*s++));
   return r;
 }
 

Strcat prototype
Extern char *strcat(char *dest,char * SRC);
usage
# include < String. H >
In C++, it exists in < cstrings > In the header file.
function
Add the SRC reference string to the end of dest (overwriting the '\0' at the end of dest) and add '\0'.
instructions
The memory area indicated by SRC and dest must not overlap and dest must have enough space to hold the SRC string.
Returns a pointer to dest.
Function implementation:

//Const the source string to indicate that it is an input parameter
char *strcat(char *strDest, const char *strSrc) 
{
  //Return address, so you cannot declare address after an assert assertion
  char *address = strDest;
  assert((strDest != NULL) && (strSrc != NULL)); //Add a non-0 assertion to the source and destination addresses
  while(*strDest)             //Is the while (* strDest! ='0')
  {
    //Using while(*strDest++) causes an error because strDest executes ++ once after the loop ends,
    //Then strDest will point to the next location of '0'. / so ++ in the circulation; Because if *strDest is last
    //Marks the end of the string '0'.
    strDest++;
  }

  while(*strDest++ = *strSrc++)
  {
    NULL;             //You can use ++ in this loop,
  }                   //StrDest ='0'; There is no necessary
  return address;     //To implement the chain operation, the destination address is returned
}

Related articles: