Is it possible to return an array?

Is it possible to create an array within a function and return it at the end of the function ?

Also what does having a pointer function mean like int *foo(/*......*/) What exactly does it return aswell.
Last edited on

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.
Last edited on
Pointers and arrays have a close relationship, you can read about it. In short, an array is essentially just a pointer to its first element.
@integralfx about your second example, what will be receiving what int *foo() is returing (i.e the array) a pointer?
Last edited on
> Is it possible to create an array within a function and return it at the end of the function ?

Arrays are not copyable types. To be able to do this, we must wrap the array in a copyable type.
There is no need to create anything home-grown for this; this (plus a convenient interface) is what std::array<> is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <array>

struct my_array { int arr[5] {}; };

my_array foo( int v )
{
    my_array ma = { { v*2, v*4, v*6, v*8, v*10 } } ;
    return ma ;
}

std::array<int,5> bar( int v )
{
    std::array<int,5> sa = { { v*2, v*4, v*6, v*8, v*10 } } ;
    return sa ;
}

int main()
{
    const auto a = foo(5) ;
    for( int v : a.arr ) std::cout << v << ' ' ;
    std::cout << '\n' ;

    const auto b = bar(5) ;
    for( int v : b ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/7cde6dde630a9ffb


> an array is essentially just a pointer to its first element.

No.

There is an implicit array-to-pointer conversion; however, that does not imply that an array is a pointer.
Topic archived. No new replies allowed.