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.
Links
- Next Article - C Programming #76: strcat implementation
- Previous Article - C Programming #74: strlen implementation
- All Article - C Programming
No comments :
Post a Comment