C++ new operator Using an array of pointers to arrays, allocating heap memory

Description

C++ new operator Using an array of pointers to arrays, allocating heap memory

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

int main()//from ww  w.  j  a  v a 2s . c  om
{
  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.
}



PreviousNext

Related