Jump to: navigation, search

Description

The strncpy() function shall copy no more than n characters from the null-terminated string pointed to by src to the memory pointed to by dest. The destination shall be padded with null characters.

Beware: A terminating null byte will not be written to the resulting dest string when the length of the src string is greater than or equal to n (this follows from the above description, it's not a new constraint).

Return value

The strncpy() function shall return the pointer dest; the function has no failure mode and no error return.

Prototype

Declared in string.h

The C90 prototype is:

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

The C99 prototype is:

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

Implementation

In standard C, this can be implemented as (adjust prototype for C99):

#include <stddef.h> /* size_t */
char *strncpy(char *dest, const char *src, size_t n)
{
    char *ret = dest;
    do {
        if (!n--)
            return ret;
    } while (*dest++ = *src++);
    while (n--)
        *dest++ = 0;
    return ret;
}

Compilable unit, portable C90 in implementation namespace; public domain; past reviewers: none; current reviews: none

References

The C Standard, 7.21.2.4 (C99)

Personal tools