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.

Categorystring.h strings
KindLibrary function
Header<string.h>
C standardC89 / C90

📝 Syntax

char *strncpy(char *dest, const char *src, size_t n);

⚙️ Parameters

dest RequiredA destination array with at least n writable character positions.
src RequiredThe source string, read up to n characters or its terminator.
n RequiredThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏