Your string "\0"
is equivalent a char[]{ 0, 0 }
. When you use strcat
it overwrites the current null terminator, copies the values up to and including the first '\0'
, so this is what happens:
// ... are garbage values
strcat(output2,first); // output2 is { 'o', 'n', 'e', '\0', ... }
strcat(output2,term); // '\0' is overwritten with `\0` so no change.
strcat(output2,second); // output2 is { 'o', 'n', 'e', 't', 'w', 'o', '\0', ... }
strcat(output2,term); // '\0' is overwritten with `\0` so no change.
To make this output one
:
output2[3] = 0;
// or this maybe easier to read
output2[3] = '\0';
As pointed out in the comments (and other answers):
output2 = malloc(20);
strcat(output2,first);
is undefined behavior since strcat
tries to find the first null character. So just set the first character to \0
:
output2 = malloc(20);
output2[0] = 0; // or '\0'
strcat(output2,first);