0

Why is it necessary to define an array as a global variable when returning an array in a function?

int v[10] = { 1,2,3,44,55,66,77,8,9,1 };
auto fun()->int(*)[10]
{
    //int v[10] = { 1,2,3,44,55,66,77,8,9,1 };/
    return &v;
}

int main()
{
    auto t = fun();
    for (int i = 0; i <= 10; i++)
        cout << (*t)[i] << endl;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Byerea
  • 3
  • 1
  • 2

1 Answers1

1

First, your code is C++ and not C, so I'll respond accordingly.

You can return a C++-style std::array, which is an object rather than a C-style array and thus can be returned by value:

#include <iostream>
#include <array>
int v[10] = { 1,2,3,44,55,66,77,8,9,1 };
auto fun()->std::array<int, 10>
{
    std::array<int, 10> v;
    v[0] = 5;
    v[1] = 32;
    //int v[10] = { 1,2,3,44,55,66,77,8,9,1 };/
    return v;
}

int main()
{
    auto v = fun();
    for(size_t i = 0; i < 10; i++) {
        std::cout << v[i] << std::endl;
    }
}   

You could have dynamically allocated the array instead, in which case you return a pointer and the caller is responsible for freeing it:

auto fun2()->int*
{
    auto v = new int[10];
    v[0] = 1;
    // assign other elements
    return v;
}

int main()
{


    auto t2 = fun2();
    for (int i = 0; i < 10; i++)
        std::cout << t2[i] << std::endl;
    delete[] t2;
}   

You're simply not allowed to allocate the array on the stack and then return it, because the lifetime of stack variables is over as soon as your function returns. With that said, this example is valid because the array is allocated in main's stack frame and outlives all of its uses:

void fillIn(int* ar, size_t len) {
    for (size_t i = 0; i < len; i++) {
        ar[i] = 32; // or whatever logic you want
    }
}
int main()
{
    int x[10];
    fillIn(x, 10);
    for (int i = 0; i < 10; i++) {
        std::cout << x[i] << std::endl;
    }
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • "You could have dynamically allocated the array instead, in which case you return a pointer" - why not just return the array by value? (as a `std::array` even). – Jesper Juhl Apr 18 '20 at 15:36
  • @JesperJuhl It's not clear that the op wants to use a C++-style `std::array` which can be returned by value easily, but I'll write it up now regardless. Beyond that, there's no good way to return a C-style array (spec section 8.3.5/8) – nanofarad Apr 18 '20 at 15:37