Jun 25, 2016

C Programming #75: strcpy implementation

C Programming #75: strcpy implementation

Following article implements our own version of strcpy implementation. Please review article strings and string.h library if not already done. Since our implementation function name would clash with standard implementation, lets prefix my_ to it. We know the prototype of my_strcpy is as follow.

/*Copy the string src to dest, 
returning a pointer to the start of dest.*/
char *my_strcpy(char *dest, const char *src);

We need to copy byte by byte from src to dest till we hit '\0' (including it). It would look like below

#include <stdio.h>
#include <string.h>

char *my_strcpy(char *dest, const char *src);

int main()
{
   char a[50] ="";
   char b[50] ="";

   printf("a before memcpy is %s\n", a);
   printf("b before memcpy is %s\n", b);

   strcpy(a, "Hello World");
   my_strcpy(b, "Hello World");

   printf("a after memcpy is %s\n", a);
   printf("b after memcpy is %s\n", b);

   return 0;
}
char *my_strcpy(char *dest, const char *src)
{
   while((*dest++ = *src++) != '\0');
   return dest;
}
a before memcpy is 
b before memcpy is 
a after memcpy is Hello World
b after memcpy is Hello World

Never use custom implementation like this, always use the standard implementation provided in glibc.

No comments :

Post a Comment