OOPortal OOPortal
Pointers/Memory Allocation   «Prev  Next»
Lesson 12 Dynamic multidimensional arrays
Objective Explore program that implements dynamic 2-dimensional array.

Dynamic Multidimensional Arrays

C++ does not allow general dynamic multidimensional arrays. Scientists, engineers, and others make heavy use of general two-dimensional arrays called matrices. It would be inconvenient to have to always write special routines for each possible row size declared.
Over the next four lessons, we will look at how a dynamically allocated two-dimensional array can be implemented. This code will be very helpful in writing the course project program.

The two dstruct

First we will declare a struct that creates the new type twod.

// Dynamic arrays in two dimensions.
struct twod {
   double**  base;
   int   row_size, column_size;

The struct declaration creates the new type twod. The two-dimensional array has its base address stored in the member base. The row and column sizes also will be stored. The underlying data structure is very simple:
  1. The pointer base is a pointer to a pointer to double.
  2. The base pointer contains the starting address of an array of pointers, and each pointer is a starting address of a row of doubles.

Next, we will look at the allocate() and deallocate() functions.