for instance,
if str = "ab"
is passed in a function returnString()
and we have a function defination like
string returnString(string str)
{
str ='c';
return str;
}
Output :- abc
but if we have function as
char* returnString(string str)
{
str ='c';
return str;
}
will give the error like :
[Error] cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'char*' in return***
How can I resolve this?
CodePudding user response:
You can use str.data()
or str.c_str()
to get a pointer to the first character, but you should never return this outside of your function. You are inviting a very swift access violation once your string gets destroyed (look carefully, str
is a local copy on the function's stack), and that's if you're lucky.
If you're trying to interface with a C API, you can strdup
that pointer before exiting the function, but make sure you understand that the new pointer needs to be free
d at some later point by you.
CodePudding user response:
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 []
.