strncpy in C language

The C strncpy function is a String Function, which is used to copy n number of characters from one string to another. The syntax of the C strncpy function is

char *strncpy(char *destination, char *source, size_t n);

Or we can simply write the arguments as (str1, str2, size);

  • source: A valid string
  • destination: This is where the function will copy the characters from Source to the destination string.
  • n: The number of characters that you want to copy from Source.

strncpy in C Example

This function is used to copy the user-specified string. This program will help you to understand the C strncpy method with multiple examples.

TIP: You must include the #include<string.h> header before using this strncpy Function.

The first statement will copy all the characters in str3 to str1 because the length of C Programming Language is less than the given size of 40.

The second statement will copy the first 9 characters present in str3 to str1 because we are restricting the size to 9.

#include <stdio.h> 
#include<string.h>

int main()
{
   	char str1[50], str2[50], str4[50];
  
   	char str3[] = "C Programming Language ";
	
   	strncpy(str1, str3, 40);		
   	printf("\n The Final = %s", str1);
   
   	strncpy(str2, str3, 9);
   	printf("\n The Final  = %s", str2);
   	
 	memset(str4, '\0', sizeof(str4));
   	strncpy(str4, "Tutorial Gateway", 16);
   	printf("\n The Final = %s", str4);
   	
}
 The Final = C Programming Language 
 The Final = C Program
 The Final = Tutorial Gateway

strncpy in C Programming language Example 2

This program allows the user to enter his/her own character array. Next, it will use the strncpy function to copy the user-specified string.

#include <stdio.h> 
#include<string.h>
 
int main()
{
	char str1[100], str2[100];
 
	printf("\n Please Enter the String that you want to Copy : ");
	gets(str2);	
	
	//memset(str1, '\0', sizeof(str1));
	strncpy(str1, str2, 7);
	
 	printf("\n The Final String after Copying = %s", str1);
	
}

Although the given string is valid, this function is only copied. This is because we restricted the copy function to the first 7 characters (including spaces).

 Please Enter the String that you want to Copy : Learn C Programming

 The Final String after Copying = Learn C

Let me change the Size value and see

strncpy in C Language 3