Jun 25, 2016

C Programming #76: strcat implementation

C Programming #76: strcat implementation

Following article implements our own version of strcat 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_strcat is as follow.

/*Append the string src to the string dest, 
returning a pointer dest*/
char *my_strcat(char *dest, const char *src);

All characters from src should be copied to dest. It is already understood that dest would have enough space to hold src. We need to first go to end of dest and then start copying. Implementation would look something like this

#include <stdio.h>
char *my_strcat(char *dest, const char *src);
int main()
{
   char a[50] = "Hello ";
   char b[50] = "Hello ";

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

   strcat(a, "world");
   my_strcat(b, "india");

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

   return 0;
}
char *my_strcat(char *dest, const char *src)
{
   char *tdest = dest;
   while (*tdest)
      tdest++;
   while (*tdest++ = *src++);
   return dest;
}
a before strcat is Hello 
b before strcat is Hello 
a after strcat is Hello world
b after strcat is Hello india

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

No comments :

Post a Comment