On this page
strncpy
Prev: strcat | Up: string.h | Next: strtok
Rel: snprintf(), string.h, stdlib.h & string.h Guide
Ref: cppreference — strncpy
Tags: #public #prog #c #stdlib #string #tier/legacy
Include
#include <string.h>
Signature & Overview
char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Not a safe string copy: omits NUL termination if strlen(src) >= n and zero-pads the entire remaining buffer.
Legacy / Avoid: Prefer snprintf() in all new code.
Notes & Pitfalls
- Does NOT guarantee NUL-termination if
strlen(src) >= n, AND zero-pads the rest of the buffer (slow on huge buffers): Always setdst[n - 1] = '\0'or usesnprintf().
Example
#include <assert.h>
#include <string.h>
int main(void) {
char dst[6];
strncpy(dst, "hello world", sizeof(dst) - 1);
dst[sizeof(dst) - 1] = '\0';
assert(strcmp(dst, "hello") == 0);
}
Linked from
Related notes
- tuts/c/stdlib/string/strcat Linked here; links to this page; shared tags: #c, #prog, #stdlib, #string, #tier
- tuts/c/stdlib/string/strtok Linked here; links to this page; shared tags: #c, #prog, #stdlib, #string, #tier
- tuts/c/stdlib/string Linked here; links to this page; shared tags: #c, #prog, #stdlib, #string
- tuts/c/stdlib/stdio/snprintf Linked here; shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/stdlib_and_string_h Linked here; shared tags: #c, #prog, #stdlib
- tuts/c/stdlib/string/memchr shared tags: #c, #prog, #stdlib, #string, #tier
- tuts/c/stdlib/string/memcmp shared tags: #c, #prog, #stdlib, #string, #tier
- tuts/c/stdlib/string/memcpy shared tags: #c, #prog, #stdlib, #string, #tier
- tuts/c/stdlib/string/memmove shared tags: #c, #prog, #stdlib, #string, #tier
- tuts/c/stdlib/string/memset shared tags: #c, #prog, #stdlib, #string, #tier