user
user

Reputation: 9

Using strcat() function in C

While concatenating C with A the result is not what I wanted. How can I get hellojames instead of helloworldjames?

char  A[12] =  "hello";
char  B[12] =  "world";
char  C[12] =  "james";

strcat(A,B);
printf("%s", A);
output = helloworld


strcat(A,C);
printf("%s",A);
output = helloworldjames

Upvotes: 0

Views: 162

Answers (2)

Mariano Macchi
Mariano Macchi

Reputation: 242

When you use strcat(A, B), the null char ('\0') marking the end of the A string gets replaced by the first char in B and all the following chars in B get appended from this point onward to A (that must be large enough to hold the result of the concatenation or undefined behaviour could occur).

After the strcat() call, A is no longer what you initially defined it to be, but a new string resulting from the concatenation.

If you want to reverse this, a simple solution is to keep A's lenght before doing the concatenation using strlen():

int A_len = strlen(A);

This way to reverse strcat(A, B) you only need to set the null char where it used to be before the concatenation:

A[A_len] = '\0';

After this replacement, strcat(A, C) returns hellojames.

Upvotes: 1

DrC
DrC

Reputation: 7698

When you do the strcat(A,B), you are modifying the string A points to. You need to create a working buffer. Something like:

char work[12];
strcpy(work, A);
strcat(work, B);
printf("%s", work);
strcpy(work, A);
strcat(work, C);
printf("%s", work);

Upvotes: 0

Related Questions