C strncat()

The strncat() function is defined in the string.h header file. It helps to concatenate two strings by appending the string pointed by src to the destination string pointed by dest up to n characters long.


char *strncat(char *dest, const char *src, size_t n); #where n should be a integer

 

strncat() Parameters: 

The strncat() function takes three parameters. The size of the destination string should be large enough to store the resultant string which includes the additional null character. if the size is not enough it will raise segmentation fault error.

Parameter Description Required / Optional
dest Pointer to the destination array contains the concatenated resulting string Required
src This is the string to be appended Required
n maximum number of characters to be appended Required

strncat() Return Value

The function returns a pointer to the resulting destination string. 

Input Return Value
success pointer to destination string

Examples of strncat() 

Example 1: Working of strncat() function in C?


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

int main()
{
   char src[40], dest[40];

   strcpy(src,  "Source is:");
   strcpy(dest, "Destination is:");

   strncat(dest, src,20);

   printf("Final destination string : |%s|", dest);
   
   return(0);

}

Output:


Final destination string : |Destination is Source is|

Example 2: How strncat() works in C?


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

int main (){

   char string1[100] = "This is ", string2[] = "learnetutorials.com";

   // the resultant string is stored in string1.
   strncat(string1, string2,15);
   puts(string1);
   puts(string2);

   return 0;
}

Output:


This is learnetutorials.com
learnetutorials.com