Implement strncpy() function in C
Write an efficient function to implement strncpy()
like function in C, which copies the given n
characters from source C-string to another string.
The prototype of the strncpy() is:
char* strncpy(char* destination, const char* source, size_t num);
The C99 standard adds the restrict qualifiers to the prototype:
char* strncpy(char* restrict destination, const char* restrict source, size_t num);
The strncpy()
function copies num characters from the null-terminated string pointed to by source to the memory pointed to by destination and 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 40 41 42 43 |
#include <stdio.h> #include <stddef.h> // Function to implement `strncpy()` function char* strncpy(char* destination, const char* source, size_t num) { // 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 first `num` characters of C-string pointed by source // into the array pointed by destination while (*source && num--) { *destination = *source; destination++; source++; } // null terminate destination string *destination = '\0'; // the destination is returned by standard `strncpy()` return ptr; } // Implement `strncpy()` function in C int main(void) { char* source = "Techie Delight"; char destination[20]; size_t num = 6; // Copies the first `num` characters of the source to destination printf("%s", strncpy(destination, source, num)); return 0; } |
Output:
Techie
The time complexity of the above solution is O(num).
Shorter Version:
1 2 3 4 5 6 7 8 |
while (*source && num--) { *destination = *source; destination++; source++; } *destination = '\0'; |
We can replace the above lines of code with a single line of code. The following code will copy the first num
characters of the source to the array pointed by destination, including the terminating null character.
1 |
while (num-- && (*destination++ = *source++)); |
That’s all about strncpy()
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 :)