This will crash because of the memory model.
In C++ (as in many other languages), there are two two popular places where you can allocate memory: the stack and the heap.
In C++, the stack is a special memory region where functions place whatever values they'll need during their execution. The most important thing to remember is that whatever lives there gets deleted once the function returns. That means that if you return a pointer to something on the stack, your program is bound to crash because whatever was there isn't anymore. That's what you'd be doing if you returned an array.
Hopefully, there's a place where data can live forever ("forever" being the duration of your program): the heap. If you allocate something on the heap, it won't get cleared away when the function returns. However, it implies additional bookkeeping, since you could easily lose all references to a certain block of allocated memory; and if you do, there's no way to reclaim it (that's called a leak, and it's a very bad thing). Therefore, a rule was suggested: if a function allocates memory on the heap, it should be responsible for freeing it. Problem is, if your function returns allocated memory, it obvisouly can't dispose of it. Therefore, you shouldn't allocate memory on the heap and return it.
So, if you can't allocate your array on the stack, and you can't return a pointer to memory on the heap, what can you do?
I suggest you use C++ types to solve your problem. If you're about to use an array of characters, the best would be a std::string
(#include <string>
). If you're about to use an array of whatever else, the best would probably be a std::vector<YourTypeHere>
(#include <vector>
). Both manage their own memory, and therefore it's safe to return them.
There's ample documentation for both on here and Google. Here's a quick example anyways.
std::vector<int> foo()
{
std::vector<int> my_vector;
my_vector.push_back(1);
my_vector.push_back(2);
my_vector.push_back(3);
return my_vector;
}
std::string bar()
{
std::string my_string = "The quick brown fox jumps over the lazy dog";
return my_string;
}
int main()
{
std::vector<int> my_vector = foo();
// will print 123
std::cout << my_vector[0] << my_vector[1] << my_vector[2] << std::endl;
std::string my_string = bar();
// will print The quick brown fox jumps over the lazy dog
std::cout << my_string << std::endl;
}