Return a char concatenation
The concatenation is working fine in both instances.

What is wrong, though, is that you can't return a pointer to a locally declared array from a function. That array no longer exists when you leave the function.

The thing to remember with arrays is that you never pass the actual array to or from a function. All you pass is a pointer to the memory address where the array is.  If you allocate an array in a function that memory is allocated on the stack. When you return the array from the function you return an address that is (currently) within the stack.  When you leave the function all memory allocated on the stack by that function is removed, and that includes your array.

There are four ways of solving the problem - all of them have their pitfalls.


Use a global "scratch pad" array that is big enough for any concatenating you may want to do. Do your concatenation in there.
Declare your array static, which means it's allocated only once and can be returned from the function - but like the global one you have to have a fixed size.
Pass a pointer to a suitably sized array to your function to have that array used for the concatenation, and
Allocate memory on the heap using malloc().


My normal method is number 3. It's the safest and most flexible:

const char *a = "part a";
const char *b = " part b";

char all[14];
doConcat(a, b, all);

void doConcat(const char *a, const char *b, char *out) {
    strcpy(out, a);
    strcat(out, b);
}