Last Updated:

Dynamic Matrix in C++

Dynamic in C++ can be not only one-dimensional arrays, but also multidimensional. Of those that are included in the class of the latter, consider two-dimensional dynamic arrays (dynamic matrices). The key object for working with them are pointers.

Using Pointers to Work with Dynamic Matrices

When working with dynamic matrices in C++, you can use regular pointers. After describing the pointer, you will need to allocate memory to store NxM elements (N is the number of rows, M is the number of columns). This is how memory is allocated to store an integer matrix of NxM size:

To allocate memory, you can also use the malloc function:

or operation new:

After allocating memory, it remains to find a way to refer to the element of the matrix. All elements of a two-dimensional array are stored in a one-dimensional array the size of the NxM elements. First in this array there is the 0th row of the matrix, then the 1st, and so on. therefore, to refer to the element Ai, j you need to use the row number i and the number of column j to calculate the number of the element k in the dynamic array. Given that in an array the elements are numbered from zero k = iM + j, the reference to the element A[i] [j] would be * (A + i * m + j).

As an example of working with dynamic matrices, consider a problem.

Task

Two matrices of the matrix of real numbers A(N, M) and B(N, M) are given. Calculate the matrix C = A + B.

Decision

As you know, the sum of matrices of the same dimension is a matrix, the elements of which are obtained by adding the corresponding elements of the original matrices. Consider a flowchart of the matrix addition algorithm.

Matrix addition program code:

 

Using Double Pointers to Work with Dynamic Matrices

The main way to work with dynamic matrices is based on the use of double pointers. Consider the following fragment of the program.

Using the new operator, an array of N elements is created, each of which is the address where the float pointer is stored. It remains to determine the meaning of this pointer. To do this, we organize a loop from 0 to N-1, in which each pointer will address the memory area where M float elements are stored.

After that, an array of N pointers is defined, each of which addresses an array of M real numbers (float type). In fact, a dynamic matrix of NxM size has been created. An element of a dynamic matrix is accessed in the same way as an element of a static matrix. To access an item ai, j in a C++ program, you must specify its name, and in square brackets the number of the row and column (a[i] [j]).

Task

Write a program for multiplying two matrices of real numbers A(N, M) and A(M, L)..

Decision

The multiplication program of two such matrices, implemented using double pointers, will look like this: