Implement strcpy function implementation method

  • 2020-04-01 21:40:27
  • OfStack


#include<iostream>
 #include <assert.h>
 using namespace std;

 void myStrcpy(char* Dest, const char *Src)
 {
     assert((Dest!= NULL)&&(Src!=NULL));
     while((*Dest = *Src)!='0')
     {
         Dest++;
         Src++;
     }
 }

 int main()
 {
     char dest[] = "helloworld";//Pay attention to
     char* src = "hello";
     myStrcpy(dest, src);
     printf("%s",dest);
     return 0;
 }

Note: in line 17, we use a character array, because if we use a character pointer, the character constant is stored in the constant area, and the pointer points to this address. You cannot modify the string by changing the pointer to the content. If you use an array of characters, you will copy "helloworld" into the array, which can be modified.

Related articles: