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


Download  Run Code

Output:

Techie

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

Shorter Version:

 
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.

Run Code

That’s all about strncpy() implementation in C.