Implement strcpy() function in C
Write an efficient function to implement strcpy() function in C. The standard strcpy() function copies a given C-string to another string.
The prototype of the strcpy() is:
char* strcpy(char* destination, const char* source);
The C99 standard adds the restrict qualifiers to the prototype:
char* strcpy(char* restrict destination, const char* restrict source);
The strcpy() function copies the null-terminated C-string pointed to by source to the memory pointed to by destination. The memory allocated to a destination should be large enough to copy the source string (including the terminating null character). Source and destination should not overlap with each other. The strcpy() function finally returns the pointer destination.
C
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <stdio.h> // Function to implement `strcpy()` function char* strcpy(char* destination, const char* source) { // return if no memory is allocated to the destination if (destination == NULL) { return NULL; } // take a pointer pointing to the beginning of the destination string char *ptr = destination; // copy the C-string pointed by source into the array // pointed by destination while (*source != '\0') { *destination = *source; destination++; source++; } // include the terminating null character *destination = '\0'; // the destination is returned by standard `strcpy()` return ptr; } // Implement `strcpy()` function in C int main(void) { char source[] = "Techie Delight"; char destination[25]; printf("%s\n", strcpy(destination, source)); return 0; } |
Output:
Techie Delight
The time complexity of the above solution is O(n), where n is the length of the source string.
Shorter Version:
|
1 2 3 4 5 6 7 8 |
while (*source != '\0') { *destination = *source; destination++; source++; } *destination = '\0'; |
We can replace the above lines of code with the following single line. It will also copy the C-string pointed by source into the array pointed by destination, including the terminating null character.
|
1 |
while ((*destination++ = *source++) != '\0'); |
That’s all about strcpy() implementation in C.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)