How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e.
- Using Dynamically Allocated Array
- Using Static Array
- Using Struct
C++
#include <iostream>
using namespace std;
int * fun()
{
int arr[100];
arr[0] = 10;
arr[1] = 20;
return arr;
}
int main()
{
int * ptr = fun();
cout << ptr[0] << " " << ptr[1];
return 0;
}
|
Warning:
In function 'int* fun()':
6:8: warning: address of local variable 'arr' returned [-Wreturn-local-addr]
int arr[100];
^
The above program is WRONG. It may produce values of 10 or 20 as output or may produce garbage values or may crash. The problem is, that we return the address of a local variable which is not advised as local variables may not exist in memory after the function call is over.
Following are some correct ways of returning an array
1. Using Dynamically Allocated Array
Dynamically allocated memory (allocated using new or malloc()) remains there until we delete it using the delete or free(). So we can create a dynamically allocated array and we can delete it once we come out of the function.
Example:
C++
#include <iostream>
using namespace std;
int * fun()
{
int * arr = new int [100];
arr[0] = 10;
arr[1] = 20;
return arr;
}
int main()
{
int * ptr = fun();
cout << ptr[0] << " " << ptr[1];
delete [] ptr;
return 0;
}
|
2. Using static Array
The lifetime of a static variable is throughout the program. So we can always create a local static array and return it.
Example:
C++
#include <iostream>
using namespace std;
int * fun()
{
static int arr[100];
arr[0] = 10;
arr[1] = 20;
return arr;
}
int main()
{
int * ptr = fun();
cout << ptr[0] << " " << ptr[1];
return 0;
}
|
3. Using struct
We can wrap the array in a structure/class and return an instance of the struct/class. The reason for this work is, that the array of members of structures is deeply copied. In the below program deep copy happens when we returned instance is copied in main.
Example:
C++
#include <iostream>
using namespace std;
struct arrWrap {
int arr[100];
};
struct arrWrap fun()
{
struct arrWrap x;
x.arr[0] = 10;
x.arr[1] = 20;
return x;
}
int main()
{
struct arrWrap x = fun();
cout << x.arr[0] << " " << x.arr[1];
return 0;
}
|
Last Updated :
14 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...