How to use Dynamically Allocated Array In C++

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++




// C++ Program to Demonstrating returning of a local array
// from a function Using Dynamically Allocated Array
#include <iostream>
using namespace std;
 
int* fun()
{
    int* arr = new int[100];
 
    // Some operations on arr[]
    arr[0] = 10;
    arr[1] = 20;
 
    return arr;
}
 
int main()
{
    int* ptr = fun();
    cout << ptr[0] << " " << ptr[1];
 
    // allocated memory must be deleted
    delete[] ptr;
    return 0;
}


Output

10 20

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.

  1. Using Dynamically Allocated Array
  2. Using Static Array 
  3. Using Struct

C++




// C++ Program to Return a Local
// Array from a function While
// violating some rules
#include <iostream>
using namespace std;
 
int* fun()
{
    int arr[100];
 
    // Some operations on arr[]
    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.

Similar Reads

Following are some correct ways of returning an array

...

1. Using Dynamically Allocated Array

...

2. Using static 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....

3. Using struct

...