
strncpy() Function in C: Copying Strings Safely
Table of Content:
strncpy( ) function copies portion of contents of one string into another string. Syntax for strncpy( ) function is given below.
Syntax
char *strncpy(char *str1, const char *str2, size_t count);
Parameters
The strncpy( )
function copies up to count characters from the string pointed to by str2 into the
array pointed to by str1. str2 must be a pointer to a null-terminated string.
In C99, str1 and str2 are qualified by restrict.
If str1 and str2 overlap, the behavior of strncpy( )
is undefined.
If the string pointed to by str2 has less than count characters, nulls will be appended to the end of
str1 until count characters have been copied.
Alternatively, if the string pointed to by str2 is longer than count characters, the resultant array
pointed to by str1 will not be null terminated.
The strncpy( )
function returns a pointer to str1.
Specified by
Methods | Description |
strncpy ( str1, str2, 4); |
It copies first 4 characters of str2 into str1. |
strncpy ( str2, str1, 4); |
It copies first 4 characters of str1 into str2. |
Program
#include#include int main( ) { char source[ ] = "Welcometoatnyla" ; char target[20]= "" ; printf ( "\nsource string = %s", source ) ; printf ( "\ntarget string = %s", target ) ; strncpy ( target, source, 5 ) ; printf ( "\ntarget string after strcpy( ) = %s\n", target ) ; return 0; }
Output
source string = Welcometoatnyla target string = target string after strcpy( ) = Welco Press any key to continue . . .
Points to be Noted
- If destination string length is less than source string, entire source string value won’t be copied into destination string.
- For example, consider destination string length is 20 and source string length is 30.
- If you want to copy 25 characters from source string using
strncpy( )
function, only 20 characters from source string will be copied into destination string and remaining 5 characters won’t be copied and will be truncated.