There is no implicit conversion from the type std::string to the type char * or const char *.
So the compiler issues the error
[Error] cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'char*' in return
You could declare and define the function the following way.
const char * returnString( std::string &str )
{
str += 'c';
return str.c_str();
}
The function changes the passed object of the type std::string.
The returned pointer will be valid while the referenced object of the type std::string is alive and is not changed.
Otherwise you need to allocate dynamically a character array. In this case the function could be defined for example like
#include <string>
#include <cstring>
char * returnString( const std::string &str )
{
auto n = str.length();
char *p = new char[ n + 2 ];
std::memcpy( p, str.c_str(), n );
p[n] = 'c';
p[n+1] = '\0';
return p;
}
You will need to remember to delete the allocated character array when it will not be required any more using the operator delete [].
char*in C++. For safety and convenience you should usestd::stringbut for a C-style interface you should at least useconst char*so you can saystr.c_str()but you have to be really careful of object lifetime, for example in yourreturnStringcallingstr.c_str()will return a dangling pointer to the internal array from the function-local string that fell out of scope.char *? Most probably there is better way to solve yourXproblem thenYwhich you have answer for.