strncpy() - Manipulation Function

How to copy specified number of characters in C++?


strncpy() is used to copy upto the characters specified in the "count" from string 2 to 1. This manipulation function returns a pointer to string 1.

Pre-conditions for using strncpy():

  • str2 must be a pointer to a null terminated string.
  • If str2 has less than the count, nulls will be appended to str1.
  • If str2 has more than the number, str1 will not be null treminated.


char * strncpy ( char * str1, const char * str2, size_t count );

Example :

#include <stdio.h>
#include <cstring.h>
int main ()
char str1 [5];
char str2 []="Source string";
strncpy (str1,str2,3);
printf ("Data copied from str2 to str1
using strncpy: %s", str1);
return 0;

Result :

Data copied from str2 to str1 using strncpy: Sou

In the above example, strncpy() manipulation function copies first three characters from "str2" to "st1". Since the size of str1 is "5", null is added to the end.

C++ Tutorial

Ask Questions

Ask Question