Pointers/Memory Allocation   «Prev  Next»
Lesson 13 Dynamic multidimensional arrays
Objective The allocate() function

Examine C++ array allocation function

The allocate() function in our dynamic, multidimensional array program is used for runtime array allocation.

void allocate(int r, int s, twod& m){
  m.base = new double*[s];
  assert (m.base);
  for (int i = 0; i < s; ++i){
     m.base[i] = new double[r];
     assert (m.base[i]);
  }  
  m.row_size = r;
  m.column_size = s;
}

allocate using new()

The allocate() function uses new to allocate:
  1. a vector of column pointers, and
  2. a row of doubles

First a column of pointers to double is allocated. Each of these pointers have the base address for a row of doubles. This space is allocated off the heap iteratively using a for loop. Notice the use of assert to test if the memory allocation was successful.