I want to return an array of chars and this is the code
char convert(string user){
int n = user.length();
char char_array[n+1];
strcpy(char_array,user.c_str()) ;
return char_array;
}
You cannot return an array from a function. You can return a pointer to the first element of such array. Good news is: That function already exists. It is the std::string::c_str method.
void foo(const char*); // <- legacy, cannot modify, must pass c-string
std::string x{"Hello World"};
foo( x.c_str() );
In your code, this char char_array[n+1]; is not valid standard C++. See here for details:
Why aren't variable-length arrays part of the C++ standard?
Moreover you attempt to return a pointer to a local array. Once the function ends the arrays lifetime has passed and the pointer is of no use. More on that here: Can a local variable's memory be accessed outside its scope?
Last (and least) you declared the function to return a char when you wanted a char*. However, fixing that won't really help due to the last point.
std::string to a char array" doesn't really make much sense. A std::string is a char array (and more)
std::string::data()to get non-constchar *to the char array that is managed by a string.char*instead ofchar. Second you want to dynamically allocate the array withchar* char_array = new char[n+1], otherwise returning the array will result in undefined behaviour. make sure to delete the allocated array when you need tochar*instead of achar. and you're trying to return a pointer to a local variable which won't work either. For the latter point read this for more information: stackoverflow.com/questions/6441218/…char char_array[n+1];is not even valid.chararray in the first place? Legacy functions that expect aconst char *can be passed yourmy_string.c_str()result. Any function that performs mutations on a non-constchar *usually has an already existing analogue forstd::stringthat bypasses c-stringiness.