# Simple 2D Array

• Definition: int A[10][7];

• Elements accessed using double []: A[5][2].

• Compiler needs the size of a row to calculate the address of A[5][2].

# Dynamic 2D Arrays: Allocating

• Allocating memory: const int ROWS = 10; const int COLUMNS = 7; int **A2; // allocate the rows A2 = new int* [ ROWS ]; // array of pointers // allocate the (pointer) elements for each row for (int row = 0; row < ROWS; row++ ) A2[ row ] = new int [ COLUMNS ];

• Array of pointers that point to 1-dimensional arrays.

• Double subscript notation A[5][2] still works.

# Dynamic 2D Arrays: Deallocating

• To deallocate memory: // delete the columns for (int row = 0; row < ROWS; row++) { delete [ ] A2[ row ]; A2[ row ] = 0; // just to be safe } // delete the rows delete [ ] A2; A2 = 0;

# 2D Vectors

• Create empty 2D vector: vector< vector< int > > intArray;

• Space between the two >'s is necessary. Why?

• Allocate memory for a vector of rows, then for each row: intArray.resize ( ROWS ); for (unsigned int i = 0; i < intArray.size( ); i++) intArray[ i ].resize( COLUMNS );

• Vector destructor deallocates memory.

# Another Way: Create a 2D Array Class

• Constructor allocates memory.

• Destructor deallocates memory.

• Overload [] operator to preserve A[5][2] syntax.

• Check array indices within bounds.

• Does not have extra array of pointers.

# A Hack?

• The root of the problem: Kernighan & Ritchie decided on A[i][j] instead of A[i,j].

• The A.at() member function is straightforward.

• Works for 3-dimensions and higher using auxiliary classes like SmartIntPtr.

• Can be made "auto-expanding" like vector.