Also what does having a pointer function mean like int *foo(/*......*/) What exactly does it return aswell.
|
That's actually a function that returns a
int*
, which is what you wanted.
You might think that it may be as simple as
1 2 3 4 5
|
int* foo()
{
int arr[]{ 1, 2, 3 };
return arr;
}
|
But the compiler warns you
warning: address of local variable 'arr' returned [-Wreturn-local-addr] |
This is because
arr
is automatically cleaned up after
foo
has finished executing.
To get around this, you would need to dynamically allocate memory.
1 2 3 4 5
|
int* foo()
{
int* arr = new int[]{ 1, 2, 3 };
return arr;
}
|
However, you'd need to keep track of the pointer returned, otherwise you'd have a memory leak.
A better way would be to return a
vector<int>
, rather than a raw pointer, that way you don't have to worry about leaking memory. Why do you need to return an array? Surely there'd be a better way to solve your problem.