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;
}
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.