How To Allocate A Dynamic Table (2D Array) With C++
#include <iostream.h>
int main ()
{
int numRows, numCols, rowNum, colNum ;
cout << "Enter the number of rows: " ;
cin >> numRows ;
cout << "Enter the number of cols: " ;
cin >> numCols ;
typedef int *iPtr ; //iPtr is pointer to int
// A is an array of pointers to int
// The name of the array is equivalent to a pointer
// to the first element of the array -- thus A is a pointer
// to a pointer to an int.
int ** A = new iPtr[numRows] ;
// Allocate an array of ints for each of the elements
// of A to point to.
for (rowNum=0; rowNum<numRows; rowNum++)
A[rowNum] = new int[numCols] ;
// Now A is a (numRows) X (numCols) array of ints.
// We intitilize and print the entries to illustrate this.
// Set each entry equal to the product of the indices
for (rowNum=0; rowNum<numRows; rowNum++)
for (colNum=0; colNum<numCols; colNum++)
A[rowNum][colNum] = rowNum*colNum ;
// Print each entry -- row by row and col by col
for (rowNum=0; rowNum<numRows; rowNum++)
{
for (colNum=0; colNum<numCols; colNum++)
cout << A[rowNum][colNum] << "\t" ;
cout << endl ;
}
return 0 ;
}