0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.