Memory Allocation

Read this section on matrices. It shows how what we learned about pointers for vectors applies to building arrays. Essentially, we are building vectors of vectors. In the C/C++ sense, the first dimension points to the rows and the second dimension points to columns for a particular row. You will note that the vector of row pointers exists in contiguous memory, and that the columns for each individual row also exists in contiguous memory. However, it is not true that the array, as a whole, exists in contiguous memory. Thus, it is not possible to calculate a single memory pointer to a particular [r][c] cell of the array.

As with arrays, C++ provides syntax to declare matrices and higher-dimensional structures:

 int geom[10][3];

With the above syntax, the matrix "geom" would be allocated at compile-time (statically) using 30 consecutive integers in memory stored "row-wise" or in "row-major" ordering (i.e., the first three elements in memory would constitute row 0, the next three row 1, etc.). We access the elements of the matrix using the usual bracket notation, e.g. "geom[6][2]" would yield the value on the 7th row and 3rd column of the matrix.

An equivalent way to achieve the above using dynamic memory allocation is to declare geom as a "pointer-to-pointer-to-int":

 int **geom = new int* [10];
 for(int i=0; i < 10; i++)
     geom[i] = new int[3];

This is complicated the first few times you go through it, so be patient:

  • The variable geom is a pointer-to-pointer-to-int, but the value to which it points is also a pointer, e.g. geom is of type "int **", but geom[0] is of type "int *".
  • The first call to new[] allocates space for an array of pointers-to-int, each of which will contain the address of the first element of each row of the matrix.
  • The calls to new[] inside the loop independently allocate each row of the matrix as an array of integers.
  • We can access the elements of the matrix with exactly the same syntax as that for the statically allocated matrix, e.g. "geom[6][2]".

Note that the static allocation of a matrix above yields a set of consecutive addresses in memory ("contiguous" memory allocation), while the dynamic method above only guarantees that each row of the matrix is contiguous. A method for dynamically allocating a matrix with contiguous storage will be described elsewhere.

To release the memory after we are finished with it, we could use:

 for(int i=0; i < 10; i++)
     delete[] geom[i];
 delete[] geom;

Notice that we have one delete[] call for every new[] call above and that the release of the rows occurs before the release of the pointers to the rows.


Source: Virginia Tech, http://sirius.chem.vt.edu/wiki/doku.php?id=crawdad:programming:memory
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Last modified: Monday, November 16, 2020, 5:26 PM