#include <iostream>
using namespace std;
template <typename T>
T** create2DArray(unsigned nrows, unsigned ncols)
{
T** ptr = new T*[nrows]; // allocate pointers
T* pool = new T[nrows*ncols]; // allocate pool
for (unsigned i = 0; i < nrows; ++i, pool += ncols )
ptr[i] = pool;
return ptr;
}
template <typename T>
void delete2DArray(T** arr)
{
delete [] arr[0]; // remove the pool
delete [] arr; // remove the pointers
}
int main(){
int rows = 6;
int columns = 3;
// allocate from the stack.
double q[rows][columns];
// allocate from the heap.
double ** a = create2DArray<double>(rows, columns);
// populate the arrays.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
a[i][j] = columns*i+j;
q[i][j] = columns*i+j;
}
}
cout << "*****************" << endl;
cout << "Array indexing method." << endl;
cout << "*****************" << endl;
// print the heap allocated array using array indexing.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << a[i][j] << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
// print the stack allocated array using array indexing.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << q[i][j] << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
cout << "Pointer dereferencing method." << endl;
cout << "*****************" << endl;
// print the heap allocated array.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << *(&a[0][0] + columns*i + j) << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
// print the stack allocated array.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << *(&q[0][0] + columns*i + j) << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
// release the memory allocated to the heap.
delete2DArray<double>(a);
return 0;
}