"coinjo" <co****@gmail.com> writes:
How to return an array from a function?
Several alternatives:
1. Use std::vector<>
std::vector<int> func(size_t sz)
{
std::vector<int> vec;
vec.reserve(sz);
for (size_t i = 0; i < sz; ++i) {
vec.push_back(i);
}
return vec;
}
2. Let the caller define the array and pass it as an argument:
void func(int* arr, size_t sz)
{
for (size_t i = 0; i < sz; ++i) {
arr[i] = i;
}
}
3. Let the function allocate an array and pass it back:
int* func(size_t sz)
{
int* arr = malloc(sz * sizeof *arr);
for (size_t i = 0; i < sz; ++i) {
arr[i] = i;
}
}
Alternative 3 is the most complex, since the caller will be
responsible for freeing the array. This needs a careful
analysis of ownership and lifetime issues.
/Niklas Norrthon