Implement strncpy() function in C

Write an efficient function to implement strncpy function in C. Standard strncpy() function copy given n characters from source C-string to another string.

 
 

The prototype of 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

Download   Run Code

Output:

Techie

The time complexity of above solution is O(num).

 

Shorter Version:

 

We can replace above lines of code by single line of code. Below code will copy first num characters of source to the array pointed by destination including the terminating null character.

 
Run Code

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz