Search code examples
c++pointersdynamic-arrays

Explanation of Using Pointers to Pointers (**) for Dynamic 2D Array Declaration in C++


Hello Stack Overflow community,

I'm currently working on a C++ project involving dynamic 2D arrays, and I'm having difficulty understanding the use of pointers to pointers (**) when declaring such arrays. Additionally, the need for a loop during the declaration process is unclear to me.

Here's a snippet of the code I'm working with:

#include <iostream>

using namespace std;

int main(){
    int **matrixPtr; // 2D array declaration
    cout << "Enter the number of rows: ";
    int row; // Defining row
    cin >> row; // Initializing the value of row from the user
    cout << "Enter the number of columns: ";
    int col; // Defining column
    cin >> col; // Initializing the value of column from users
    matrixPtr = new int *[row]; // Allocating 2D array dynamically

    // Loop for dynamic allocation of each row
    for(int i = 0; i < row; i++){
       matrixPtr[i] = new int[col];
    }
    // Rest of the code...

Could someone please explain why pointers to pointers (**) are used in this context and why a loop is necessary during the dynamic allocation process? Any insights, clarifications, or code examples would be greatly appreciated.


Solution

  • Roughly a 2D matrix is just a 1D matrix whose elements are 1D matrix of elementary elements, thus an array of array. Right?

    Then if you want to allocate it dynamic you have:

    1. the type for the elements, say int,
    2. the type for storing a dynamic array of elements, then int *, pointer to int; how many, say cols,
    3. the type for storing a dynamic array of 1D-arrays, then int **, pointer to pointer to int, how many, say rows.

    Then you need a loop at (3) because you need to allocate independently each 1D-array of size cols... You have rows rows each one of size cols.