Using an array of pointers to arrays, allocating heap memory using new. - C++ Operator

C++ examples for Operator:new

Description

Using an array of pointers to arrays, allocating heap memory using new.

Demo Code

#include <iostream>
#include <iomanip>
#include <cmath>

int main()/*from  w w w .j ava 2 s .  c o m*/
{
  const int n_arrays {3};           // Number of arrays
  const int dimension {6};          // Dimension of each array
  auto arrays = new int*[n_arrays];

  for (int i {}; i < n_arrays; ++i)
    arrays[i] = new int[dimension];

  int value {};

  for (int j {}; j < dimension; ++j){
    value = j + 1;
    for (int i {}; i < n_arrays; ++i){
      arrays[i][j] = std::pow(value, i + 1);
    }
  }

  std::cout << "The values in the arrays are:\n";

  for (int i {}; i < n_arrays; ++i){
    for (int j {}; j < dimension; ++j){
      std::cout << std::setw(5) << arrays[i][j];
    }
    std::cout << std::endl;
  }

  for (int i {}; i < n_arrays; ++i)
    delete[] arrays[i];                       // First the arrays...

  delete[] arrays;                            // ...then the array of pointers.
}

Result


Related Tutorials