The following sets
chararray to “
abc\0\0\0”:
char chararray[6];
(void)strncpy(chararray, "abc", sizeof(chararray));
The following sets
chararray to “
abcdef”:
char chararray[6];
(void)strncpy(chararray, "abcdefgh", sizeof(chararray));
Note that it does
not NUL-terminate
chararray because the length of the source string is greater than or equal to the length parameter.
strncpy()
only NUL-terminates the destination string when the length of the source string is less than the length parameter.
The following copies as many characters from
input to
buf as will fit and
NUL-terminates the result. Because
strncpy() does
not guarantee to
NUL-terminate the string itself, this must be done explicitly.
char buf[1024];
(void)strncpy(buf, input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
This could be better and more simply achieved using
strlcpy(3), as shown in the following example:
(void)strlcpy(buf, input, sizeof(buf));
Note that because
strlcpy(3) is not defined in any standards, it should only be used when portability is not a concern.