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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of