strncpy() Copy at most a specified number of characters
strncpy() Copy at most a specified number of characters
strncpy() copies at most n characters. If src reaches n, no terminator is added; append one when needed. Overlapping src/dest causes undefined behavior.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
char *strncpy(char *dest, const char *src, size_t n);
⚙️ Parameters
| dest Required | A destination array with at least n writable character positions. |
|---|---|
| src Required | The source string, read up to n characters or its terminator. |
| n Required | The maximum number of character positions written in dest. |
Returns: Returns dest.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Hello
⚠️ Warning If no null character occurs among the first n source characters, dest is not automatically null-terminated. The example reserves the last byte and terminates explicitly.
💡 Tip If the source is shorter than n, strncpy() pads dest with additional null characters until all n positions have been written.
🏷️ Related string.h functions
📚 Related Tutorials
❓ FAQ
QDoes strncpy always null-terminate the destination?
ANot always. The null character is copied only if it occurs within the first n source characters. A truncated copy needs an explicitly reserved terminator.
QWhy does strncpy sometimes fill the rest of the destination with zeros?
AThat padding is required by the standard: after the source ends, null characters are written until n positions have been filled, producing a fixed-size record.
QShould strncpy's n be based on the source length or the destination capacity?
An is the maximum number of characters written to the destination and must first stay within its writable capacity. If you need a C string, normally reserve one byte and add the terminator explicitly. Basing n only on the source length can ignore destination space, while blindly using the destination capacity can cause truncation; consider both values and the intended use.