Lesson 12 | Dynamic multidimensional arrays |
Objective | Explore program that implements dynamic 2-dimensional array. |
C++ 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 struct
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;
};
struct Declaration
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:
- The pointer
base
is a pointer to a pointer to double
.
- 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.