strncat() Function in C: Concatenating Strings Safely

Rumman Ansari   Software Engineer   2024-07-05 04:20:02   9588  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

strncat( ) function in C language concatenates (appends) portion of one string at the end of another string. Syntax for strncat( ) function is given below.

Syntax

char *strncat(char *strng1, const char *strng2, size_t count);
Method Description
strncat ( strng2, strng1, 3 );  First 3 characters of strng1 is concatenated at the end of strng2.
strncat ( strng1, strng2, 3 ); First 3 characters of strng2 is concatenated at the end of strng1.

Parameters

The strncat( ) function concatenates not more than count characters of the string pointed to by strng2 to the string pointed to by strng1 and terminates strng1 with a null. The null terminator originally ending strng1 is overwritten by the first character of strng2. The string strng2 is untouched by the operation. If the strings overlap, the behavior is undefined.

In C99, strng1 and strng2 are qualified by restrict. The strncat( ) function returns strng1.

Remember that no bounds checking takes place, so it is the programmer's responsibility to ensure that strng1 is large enough to hold both its original contents and also those of strng2.

Program 1

#include 
#include 
int main(void)
{
	char s1[80], s2[80];
	unsigned int len;
	gets(s1);
	gets(s2);
	/* compute how many chars will actually fit */
	len = 79 - strlen(s2);
	strncat(s2, s1, len);
	printf(s2);
	return 0;
}

Output

 Hello
Hi
Hi HelloPress any key to continue . . .

Program 2

#include 
#include 
int main( )
{
   char source[ ] = "Welcome" ;
   char target[ ]= "C tutorial" ;
 
   printf ( "\nSource string = %s", source ) ;
   printf ( "\nTarget string = %s", target ) ;
 
   strncat ( target, source, 5 ) ;
 
   printf ( "\nTarget string after strncat( ) = %s", target ) ;
}

Output

In this program, first 5 characters of the string "Welcome" is concatenated at the end of the string "C tutorial" using strncat( ) function and result is displayed as "C tutorial Welco".


Source string = Welcome
Target string = C tutorial
Target string after strncat( ) = C tutorialWelco