What is strncpy() Function in C language?

CServer Side ProgrammingProgramming

The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where, the length of src is less than that of n, the remainder of dest will be padded with null bytes.

An array of characters is called a string.


Following is the declaration for an array −

char stringname [size];

For example − char string[50]; string of length 50 characters


  • Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants −
char string[10] = "Hello":;

Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.

The strncpy( ) function

  • This function is used for copying ‘n’ characters of source string into destination string.

  • The length of the destination string is greater than or equal to the source string.

The syntax is as follows −

strncpy (Destination string, Source String, n);

Example program

Following is the C program for strncpy() function −

main ( ){
   char a[50], b[50];
   printf ("enter a string");
   gets (a);
   strncpy (b,a,3);
   b[3] = '\0';
   printf ("copied string = %s",b);
   getch ( );


When the above program is executed, it produces the following result −

Enter a string : Hello
Copied string = Hel

It is also used for extracting substrings.

Example 1

The following example shows the usage of strncpy() function.

char result[10], s1[15] = "Jan 10 2010";
strncpy (result, &s1[4], 2);
result[2] = ‘\0’


When the above program is executed, it produces the following result −

Result = 10

Example 2

Let’s see another example on strncpy.

Given below is a C program to copy n number of characters from source string to destination string using strncpy library function −

void main(){
   //Declaring source and destination strings//
   char source[45],destination[50];
   char destination1[10],destination2[10],destination3[10],destination4[10];
   //Reading source string and destination string from user//
   printf("Enter the source string :");
   //Extracting the new destination string using strncpy//
   printf("The first destination value is : ");
   destination1[2]='\0';//Garbage value is being printed in the o/p because always assign null value before printing O/p//
   printf("The second destination value is : ");
   printf("The third destination value is : ");
   //Concatenate all the above results//
   printf("The modified destination string :");
   printf("%s3",destination1);//Is there a logical way to concatenate numbers to the destination string?//


When the above program is executed, it produces the following result −

Enter the source string :Tutorials Point
The first destination value is : Tu
The second destination value is : s
The third destination value is : i
The modified destination string :Tusi3
Updated on 19-Mar-2021 09:50:54