On this page
  1. strncpy
  2. Include
  3. Signature & Overview
  4. Notes & Pitfalls
  5. Example

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

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