In this tutorial, we are going to understand how we can return an array from a function in C++.
Typically, returning a whole array to a function call is not possible. We could only do it using pointers.
Moreover, declaring a function with a return type of a pointer and returning the address of a C type array in C++ doesn’t work for all cases. The compiler raises a warning for returning a local variable and even shows some abnormal behavior in the output.
Hence, returning an array from a function in C++ is not that easy. But we can accomplish that by following any of the below mentioned methods.
Let’s get right into it.
As we mentioned earlier, returning a normal array from a function using pointers sometimes gives us unexpected results. But this behaviour and warnings can be avoided by declaring the array to be a static
one.
Let us see how.
Output:
Here, we have declared the function demo()
with a return type int *
(pointer) and in its definition, we have returned a
(serves as both array name and base address) to site of the function call in main()
.
As we can see from the above output, the array is successfully returned by the function.
We can also make a function return an array by declaring it inside a structure in C++. Let us see how.
Output:
Here, note that we have declared the array arr
inside the structure demo
. And this time the function has a return type of the structure itself and return demo_mem
(structure variable) instead of the array.
In this way using another structure variable a
, we can access the array arr
in the main()
function.
For std::array
in C++, returning the array name from a function actually translates into the the whole array being returned to the site of the function call.
Output:
Hence it is clear from the output, that the array return by the function func()
was successful.
So in this tutorial, we learned about the different methods by which we can return an array from a C++ function.
For any further questions, feel free to use the comments below.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.