How to create a dynamic array in C++

The normal (static ) arrays have their size initialized in compile time. Although, they are useful in some cases most of the time it is required to initialize arrays size in runtime. This can be done with the help of dynamic memory allocation provided in C++. But working with dynamic memory requires proper memory management because it will inevitably lead to memory leaks.

Creating dynamic arrays:

Dynamic arrays can be created using the new[] operator. The allocated memory is stored as a pointer which can be also used with array notation i.e. The subscript operator([]). But the allocated memory must be deleted using the delete[] operator. If not performed it will lead to memory leaks in the program.

The following code illustrates how to create a dynamic array :

#include <iostream>
int main()
{
  size_t n=1;
  while (n != 0)
  {
    std::cout << "enter the number of elements in the array or 0 to exit: "; std::cin >> n;
    int* ar = new int[n]; //ar is the dynamic array
    if (n > 0)
    {
      std::cout << "enter the array elements\n";
      for (int i = 0; i < n; i++)
      {
        std::cin >> ar[i];
      }

      std::cout << "The numbers in reverse are:\n";
      for (int i = n - 1; i >= 0; i--)
      {
        std::cout << ar[i] << " ";
      }
      std::cout << std::endl;
      delete[] ar; // if this is no perfored then the allocated memory will continue to exist in the next loop iteration
    }
  }
}
Output:
enter the number of elements in the array or 0 to exit: 5
enter the array elements
1 2 3 4 5
The numbers in reverse are:
5 4 3 2 1
enter the number of elements in the array or 0 to exit: 0

Best practices in dynamic memory allocation in C++:

It is always easy to forget using the delete[] functionality and this will potentially not have many not-so-easy problems to fix.

A better way to work with dynamically allocated arrays is by using smart pointers from STL. Smart pointers support everything that a normal pointer does except pointer arithmetic. However, the pointer arithmetic feature is extremely insignificant and verbose when working with arrays.

With smart pointers, we don’t have to worry about deleting the memory because it is automatically done when the pointer object goes out of scope.

The following code illustrates the use of smart pointers to create arrays:

#include <iostream>
#include <memory>
int main()
{
  size_t n=1;
  while (n != 0)
  {
    std::cout << "enter the number of elements in the array or 0 to exit: "; std::cin >> n;
    std::unique_ptr<int[]> ar(new int[n]);
    if (n > 0)
    {
      std::cout << "enter the array elements\n";
      for (int i = 0; i < n; i++)
      {
        std::cin >> ar[i];
      }

      std::cout << "The numbers in reverse are:\n";
      for (int i = n - 1; i >= 0; i--)
      {
        std::cout << ar[i] << " ";
      }
      std::cout << std::endl;
    
    }
    // here it is not essential to use the delete operator.
  }
}

This code works exactly like the above code but here it is not required to explicitly delete the dynamic memory which is automatically done by the smart pointers destructor.

Conclusion:

Creating a dynamic array by dynamically allocating memory and using smart pointers is always an option but the C++ STL provides much better versions of dynamic arrays like the vector<> container. These containers should be mostly preferred when working with dynamic arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *