Write a program to implement your own strcpy() function

No replies
shashwat
Offline
Last seen: 1 year 37 weeks ago
Joined: 2009-02-18
bOt Points: 1160

The function mystrcpy() below implements strcpy() function and copies source string to the destination string. It returns a pointer to the destination string. Check out the code below:

#include<stdio.h>

char *mystrcpy(char * destination, const char * source)
{
  char *destination_ptr;
  /* Store the starting position 
     of the destination string */
  destination_ptr = destination;
  
  /*Copy the value at source 
    pointer to destination pointer 
    and increment both the pointers 
    until NULL is encountered.*/
  while(*destination++=*source++);
  
  /*Return the pointer 
    which is pointing to the 
    beginning of the destination 
    string*/ 
  return(destination_ptr);
}

int main()
{
  char source[] = "This is the source string";
  char destination[50];
  printf("%s",mystrcpy(destination,source));
}

Output:

Screenshot for implementing your own strcpy() function 

The above OUTPUT was generated by bOtskOOl Online Compiler - Try it out now>>

While implementing our own function similar to strcpy() we need to ensure that source string shouldn't change. Hence, we have used const before for the source (const char * source).

Founder and Admin