strncpy
function is a string processing function in the C language standard library, which is used to copy the specified length of a string to another string.
strncpy Function Header File
strncpy
function's header file is <string.h>
. Before using strncpy
function, make sure to include this header file in your C code:
#include <string.h>
strncpy Function Prototype
char *strncpy(char * restrict s1,
const char * restrict s2,
size_t n);
The strncpy
function copies no more than n
characters (characters following the null character '\0'
are not copied) from the array pointed to by s2
to the array pointed to by s1
. If copying occurs between overlapping objects, the behavior is undefined.
If the length of the array pointed to by s2
is a string shorter than n
characters, strncpy
will fill the array pointed to by s1
with '\0'
until a total of n
characters are written;
If the length of the array pointed to by s2
is a string greater than or equal to n
characters, strncpy
will not automatically add '\0'
.
Parameter Description
s1
: Pointer to the target string, indicating the location where the copied string is stored.s2
: Pointer to the source string, indicating the string to be copied.n
: The maximum number of characters to be copied (not necessarily the actual number of characters copied).
Return Value
strncpy
function returns the pointer of the target string, which is the value of s1
;
strncpy Example Code
Example 1: Copy a string and automatically fill in the terminator
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, world!";
char dest[20];
// The target space is large enough
// Will use '\0' to fill the rest
strncpy(dest, src, sizeof(dest));
printf("%s\n", dest);
return 0;
}
Example 2: Manually adding a terminator
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[10];
strncpy(dest, src, 5);
// Copy only the first 5 characters
// When the source string length is greater than or equal to n
// strncpy does not automatically add '\0'
dest[5] = '\0'; // Need to add the terminator manually
printf("%s\n", dest);
return 0;
}