C programming strncat string.h

In C programming the <string.h> strncat function append a specified number of characters to another string.This function is same a ‘strcat’ but more secure in the sense that we can limit the number of characters concatenated and so there is no risk of appending characters beyond the available space.The declaration of the function is given below.

char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);

s1 -The first string.

s2 -The string to be appended to the first string.

n -The number of characters appended to the first string.

Return type
char* -Returns the value of s1.

The maximum number of characters that can end up in the s1 array after calling the ‘strncat’ function is ‘strlen(s1)+n+1‘.The last plus 1 is for null-terminating character.And note if the string location that is read from and written to overlap the behavior is undefined.

Code example

char s1[20] = “strncat”, s2[] = ” function” , *s3 ;

s3=strncat(s1 , s2 , strlen(s2)+1 );

printf(“s1=%s \ns3=%s” , s1 , s3);


s1=strncat function
s3=strncat function

Some points to note

i)If the number of characters appended is lesser than ‘n’ or null-terminating character occurs before ‘n’ characters are appended

By default the function ‘strncat’ will always try to append ‘n’ characters to the first string but if the string to be appended has lesser than ‘n’ characters or null-terminating character is reached before ‘n’ number of characters is appended,a null-terminating character is automatically appended at the end after appending the string.

Code example

char s1[20] = “New “, s2[] = “call” , *s3 ;

s3=strncat(s1 , s2 , 10 );

printf(“s1=%s \ns3=%s” , s1 , s3);


s1=New call
s3=New call

ii)If the destination location has lesser memory storage than the required number of characters to be appended

You must always make sure that the destination location has enough storage to hold the required incoming string.If the storage is not sufficient you will get ans unexpected output.

Code example

char s1[7] = “New “, s2[] = “call” , *s3 ;

s3=strncat(s1 , s2 , 15 );

printf(“s1=%s \ns3=%s” , s1 , s3);

In VS running the program throws an exception and in Code::blocks, the output is undefined.

Related links

->C strcat string.h