C – Strcat 2017-08-06T09:22:52+00:00

Strcat :

Syntax :
char *strcat( char *str1, const char *str2 );

strcat(str1,str2) concatenates a copy of the string pointed to by str2 to the the string pointed to by str1 and terminates str1 with a null. The first character of str2 overwrites the null terminator originally ending sr1. The str2 is untouched by the operation.In this function we will pass two arguments str1,str2 as parameters.



str1[30]= www.cprogramming and str2[15]=expert.com
if we are using function as strcat(str1,str2) and print the output. It will be www.c-language.com.
i.e the last character in the first parameter get erased and second parameter concatenated in memory str1 is stored like this “www.cprogramming\0” and str2 like this “expert.com\0” after concatenation str1 is “www.c-language.com\0″ and str2 is”expert.com\0”.
So make sure that the size of str1 is large enough to accomodate all the characters in str1 and str2.


In this example I have declared size of str1 equal to 30 and str2 equal to 15.

Now you may think why I have declared str1 as 30 and str2 as 15. It’s just because I want you to undestand the concepts .OK

So if you know exact size of the string declare that size to save memory. Here str1[27] is enough, str2[11] is enough.

One more thing , what will happen if you are declaring the string like char *str1,*str2 , here no garbage values will come.
Before concatenation size of str1 is 16 & str2 is 10 and a fter concatenation size of str1 is 26 & str2 is 10. so we Saved memory.


Output :

Before concatenation :

str1: www.learner


After concatenation :

str1: www.leranermode.com


Prev Next