I am fairly new to C++ and have been avoiding pointers. From what I\'ve read online I cannot return an array but I can return a pointer to it. I made a small code to test it
Your code is OK. Note though that if you return a pointer to an array, and that array goes out of scope, you should not use that pointer anymore. Example:
int* test (void)
{
int out[5];
return out;
}
The above will never work, because out
does not exist anymore when test()
returns. The returned pointer must not be used anymore. If you do use it, you will be reading/writing to memory you shouldn't.
In your original code, the arr
array goes out of scope when main()
returns. Obviously that's no problem, since returning from main()
also means that your program is terminating.
If you want something that will stick around and cannot go out of scope, you should allocate it with new
:
int* test (void)
{
int* out = new int[5];
return out;
}
The returned pointer will always be valid. Remember do delete it again when you're done with it though, using delete[]
:
int* array = test();
// ...
// Done with the array.
delete[] array;
Deleting it is the only way to reclaim the memory it uses.