auto function(int i) -> int(*)[10]{
}
Can anyone help me how to return a pointer to array of 10 integers using trailing return type? Any example will be helpful.
First you need to decide where the integers will be stored, how they'll be "shared", and whether the caller or callee is responsible for their lifetime.
Options include...
1) returning a pointer to newly dynamically allocated memory:
auto function(int i) -> int(*)[10] {
int* p = new int[10];
p[0] = 1;
p[1] = 39;
...
p[9] = -3;
return (int(*)[10])p;
}
// BTW it's usually cleaner (avoiding the ugly cast above) to handle
// arrays via a pointer (but you do lose the compile-time knowledge of
// array extent, which can be used e.g. by templates)
int* function(int i) {
int* p = ...new and assign as above...
return p;
}
// either way - the caller has to do the same thing...
void caller()
{
int (*p)[10] = function();
std::cout << p[0] + p[9] << '\n';
delete[] p;
}
Note that 99% of the time returning either a std::vector<int>
or a std::array<int, 10>
is a better idea, and that 99% of the remaining time it's better to return a std::unique_ptr<int[]>
which the caller can move to their own variable, which will delete[]
the data as it is destroyed by going out of scope or - for member variables - destruction of containing object.
2) returning a pointer to a function()
-local static
array (which will be overwritten each time function
is called, such that old returned pointers will see the updated values and there could be race conditions in multithreaded code):
auto function(int i) -> int(*)[10]{
static int a[10] { 1, 39, ..., -3 };
return &a;
}
The caller calls this the same way, but must not call delete[]
.
an int argument and return a pointer to an array of 10 ints which means that we pointed every int element in an array of ten int. trailing return types are used for to read easily
to return a pointer to an array of ten int