C – Strcat

C – Strcat 2017-07-19T23:53:34+00:00

Strcat :

Syntax :
#include<string.h>
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.

C – STRCAT EXAMPLE PROGRAM :

 

Here
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.cprogrammingexpert.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.cprogrammingexpert.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.

C – STRCAT EXAMPLE PROGRAM :

Output :

Before concatenation :

str1: www.learner

str2:mode.com

After concatenation :

str1: www.leranermode.com

str2:mode.com 

Prev Next