Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;