Question:
Can a function return an array in c++?
Viorel
2012-05-25 12:47:13 UTC
array int a[2]={1,2,};
srr formy english
Four answers:
oops
2012-05-25 13:11:33 UTC
Not that kind of array, no. But you can return a vector:



    #include

    std::vector foo()

    {

        std::vector v = {1, 2};

        return v;

    }



There is also a template class called array, and you can return one of those:



    #include

    std::array foo()

    {

        std::array a = {1, 2};

        return a;

    }



Edit:

Don't do what peteams is suggesting. That is a terrible idea, and his last sentence explains why. If you allocate in a function, you should de-allocate in the same function. You should never leave it to someone else, that's a recipe for memory leaks. This isn't C, it's C++. We don't need to manage memory manually like that.
pressler
2017-01-11 09:55:21 UTC
i will 2nd the two ultimate posts above with 2 different opportunities: utilising structures encapsulating arrays and using static key-word. Ex: int* getArray(){ static int array[5] = {one million, 2, 3, 4, 5}; return array; }
peteams
2012-05-25 13:47:03 UTC
A C-style array is not significantly different from a pointer to the first element of the array.



So code like the following is perfectly valid



int* GetNumbers()

{

int* par = new int[2];

par[0] = 1;

par[1] = 71;

return par;

}



This allocates memory dynamically, and it is the callers responsibility to dispose of the memory.
kung_food_chicken
2012-05-25 12:50:54 UTC
Not directly no.



However you can return a pointer to an array.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...