Return array from function by reference in C++
Here we will learn how to return an array by reference from a function in C++.
We can achieve this in multiple ways. Let’s check these out:
First Method: by creating the array dynamically and returning the pointer
C++ doesn’t allow us to return an array from a function directly however we can return a pointer to the array from a function. For this purpose, we will create the array dynamically and return the pointer to the first element. And thus we can produce our array. Let’s see the code implementation to understand it better:
Suppose we want to create a function that takes an array as input and returns the prefix-sum array. We can implement it this way-
#include<bits/stdc++.h> using namespace std; int* prefixArray(int *arr,int n){ // create a new array to store prefixSum of given array int* pa=new int[n]; // find out prefixSum pa[0]=arr[0]; for(int i=1;i<n;i++){ pa[i]=pa[i-1]+arr[i]; } // return the pointer to first element return pa; } int main(){ int n=6; int arr[6]={2,3,5,6,-2,1}; //Function call int* PA = prefixArray(arr,n); //Output the prefix array for(int i=0;i<n;i++){ cout<<PA[i]<<" "; } cout<<endl; return 0; }
Output: 2 5 10 16 14 15
In some cases, you might also need the size of the array returned from the function. [Note: In the above case we have used the previously given size n]. In that situation, we can return a pair containing the pointer to the array’s first element and the returned array’s size. See the below implementation:
#include<bits/stdc++.h> using namespace std; pair<int*,int> prefixArray(int *arr,int n){ int* pa=new int[n]; pa[0]=arr[0]; for(int i=1;i<n;i++){ pa[i]=pa[i-1]+arr[i]; } //return a pair which contains array pointer and size return {pa,n}; } int main(){ int n=6; int arr[6]={2,3,5,6,-2,1}; // function call pair<int*,int>p = prefixArray(arr,n); int *PA =p.first; int size =p.second; for(int i=0;i<size;i++){ cout<<PA[i]<<" "; } cout<<endl; return 0; }
Output:2 5 10 16 14 15
Second Method: Declare array as a static member and return the pointer
If the size of the array to be returned is constant we can use this method. We will declare the array as a static member and return it in the form of a pointer.
#include<bits/stdc++.h> using namespace std; // size should be constant because we are creating static array #define n 6 int* prefixArray(int *arr){ // create a new array to store prefixSum of given array static int pa[n]; // find out prefixSum pa[0]=arr[0]; for(int i=1;i<n;i++){ pa[i]=pa[i-1]+arr[i]; } // return the pointer to first element return pa; } int main(){ int arr[6]={2,3,5,6,-2,1}; //Function call int* PA = prefixArray(arr); //Output the prefix array for(int i=0;i<n;i++){ cout<<PA[i]<<" "; } cout<<endl; return 0; }
Output:2 5 10 16 14 15
PS: You can also use vectors instead of arrays available in C++ STL which are easier to return from a function.
Leave a Reply