C++ strncpy()

strncpy() prototype

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

The strncpy() function takes three arguments: dest, src and count. It copies a maximum of count characters from the string pointed to by src to the memory location pointed to by dest.

If count is less than the length of src, first count characters are copied to dest and it is not null terminated. If count is more than the length of src, all the characters from src is copied to dest and additional terminating null characters are added until a total of count characters have been written.

The behaviour is undefined if the strings overlap.

It is defined in <cstring> header file.

strncpy() Parameters

  • dest: Pointer to a character array where the contents are copied to.
  • src: Pointer to a character array where the contents are copied from.
  • count: Maximum number of characters to copy.

strncpy() Return value

The strncpy() function returns dest, the pointer to the destination memory block.

Example: How strncpy() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char src[] = "It's Monday and it's raining";
    char dest[40];

    /* count less than length of src */
    strncpy(dest,src,10);
    cout << dest << endl;

    /* count more than length of src */
    strncpy(dest,src,strlen(src)+10);
    cout << dest << endl;
    return 0;
}

When you run the program, the output will be:

It's Monday
It's Monday and it's raining