I am a C++ noob and I wanna know how can i return an array from a C++ function.
I tried the following code but doesn’t seem to work.
char some_function(){
char my_string[] = "The quick brown fox jumps over the lazy dog";
return my_string;
}
The reason that code isn’t working is that the minute the function ends, so does the lifetime of the string you have created. Instead, if you’re going to be working in C++ use
std::stringand return that.For other arrays use
std::vector,std::dequeor one of the other STL classes. I’d also point you to look at the STL (standard template library):On returning arrays:
The big problem with pointers and such is object lifetime considerations. Such as the following code:
what happens here is that when the function exits
myIntno longer exists leaving the pointer that was returned to be pointing at some memory address which may or may not hold the value of 4. If you want to return an array using pointers (I really suggest you don’t and usestd::vector) it’ll have to look something like:which uses the new operator.