In this article, we are going to learn how to return an array from a function in C++. We often work on arrays inside a function and then we need to return this array to the calling function. In this post, we will learn different ways of how to return an array from a function to its calling function.
We will learn this by using multiple methods. The methods that we are going to learn are:
- Using Pointer return an array from Function in C++
- Using std::array to return array from Function in C++
1. Using Pointer return an array from Function in C++
In this example, we are going to see how we can pass an array to a function, and then this function will work on this array and return this array back to us.
We will pass the array by reference and we will get the array pointer back from the function with the modified values.
We will get a new array which is the result of the logic done by the function we called on this array.
This function is generating the square of each element of the original array.
#include <iostream>
using namespace std;
#define SIZE 10
int *Square(int arr[], int size){
for (int i = 0; i < size; ++i) {
arr[i] *= arr[i];
}
return arr;
}
int main(){
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < SIZE; ++i) {
cout <<"The elements of array are: " <<arr[i] << "\n ";
}
int *arrptr = Square(arr, SIZE);
for (int i = 0; i < SIZE; ++i) {
cout <<"The Square of each element of array are: " <<arrptr[i] << "\n ";
}
return 0;
}
Output
The elements of array are: 1
The elements of array are: 2
The elements of array are: 3
The elements of array are: 4
The elements of array are: 5
The elements of array are: 6
The elements of array are: 7
The elements of array are: 8
The elements of array are: 9
The elements of array are: 10
The Square of each element of array are: 1
The Square of each element of array are: 4
The Square of each element of array are: 9
The Square of each element of array are: 16
The Square of each element of array are: 25
The Square of each element of array are: 36
The Square of each element of array are: 49
The Square of each element of array are: 64
The Square of each element of array are: 81
The Square of each element of array are: 100
2. Using std::array to return array from Function in C++
#include <iostream>
#include<array>
using namespace std;
auto Getarray()
{
std::array<int,10> arrtest;
for(int i = 0;i < arrtest.size() ;i++)
{
arrtest[i] = i ;
}
return arrtest;
}
int main()
{
auto arr=Getarray();
cout<<"The function returned array is : \n";
for(int i=0;i < arr.size(); i++)
{
cout<<arr[i]<<"\n";
}
return 0;
}
Output
The function returned array is :
0
1
2
3
4
5
6
7
8
This program will work on C++ 14 onwards because we are using auto as the return type for the function Getarray().
If you are using older versions of C++ then please try to use the below declaration.
std::array Getarray()