// ==========================================================================
// $Id: dynamic2d.cpp,v 1.2 2008/09/13 01:36:52 jlang Exp $
// CSI2372 example Code for lecture 3
// ==========================================================================
// (C)opyright:
//
//   Jochen Lang
//   SITE, University of Ottawa
//   800 King Edward Ave.
//   Ottawa, On., K1N 6N5
//   Canada. 
//   http://www.site.uottawa.ca
// 
// Creator: jlang (Jochen Lang)
// Email:   jlang@site.uottawa.ca
// ==========================================================================
// $Log: dynamic2d.cpp,v $
// Revision 1.2  2008/09/13 01:36:52  jlang
// Minor clarifications arrays and operators
//
// Revision 1.1  2006/09/11 21:38:35  jlang
// Check-in for lecture 3
//
//
// ==========================================================================
#include <iostream>
#include <iomanip>

using std::cout;
using std::endl;
using std::setw;


/** Print a 2D array by passing the array as an array of pointer to pointer
 *  Will not work with multi-dimensional arrays or semi-dynamic arrays
 *  since types cannot be converted. 
 */
void printIntArray2D_ptr_ptr( int **numbers, 
			      const int numRows, const int numCols ) {
  for (int r=0;r<numRows;r++) {
    for (int c=0;c<numCols;c++) {
      cout << setw(10) << numbers[r][c] << '\t';
    }
    cout << endl;
  }
  cout << endl;
}


/** Print a 2D array by passing a pointer to type
 *  Memory layout must be contiguous. */
void printIntArray2D_ptrType( int *numbers, 
			      const int numRows, const int numCols ) {
  for (int r=0;r<numRows;r++) {
    for (int c=0;c<numCols;c++) {
      cout << setw(10) << numbers[r*numCols+c] << '\t';
    }
    cout << endl;
  }
  cout << endl;
}

int main() {
  // All dimensions are determined at runtime
  int numRows = 3, numCols = 4;
  int **numbers = new int*[numRows]; 
  for(int r=0; r<numRows; r++) {
    numbers[r] = new int[numCols];
    for(int c=0; c<numCols; c++) {
      numbers[r][c] = r*numCols + c;
    }
  } 
  // Print the array of pointer to pointers
  printIntArray2D_ptr_ptr(numbers, numRows, numCols ); 
  // Memory layout may cause seg fault or printing of  garbage
  printIntArray2D_ptrType(&numbers[0][0], numRows, numCols ); 

  for(int r=0; r<numRows; r++) {
    delete[] numbers[r];
  }
  delete [] numbers;
  return 0;
}
