Search code examples
c++traversaldynamic-arrays

2D Dynamic array in C++


If I declare a 2D dynamic array in C++ using the following code:

int *arr2D[2];              //allocating rows statically
for(int i=0;i<2;i++)
{
     arr2D[i]=new int[6];   //for each row, 6 columns are dynamically allocated
}

Then how should I enter and display values in this 2D dynamic array using loops? (issues with dynamic array traversal for entering and displaying values in it after its allocation)


Solution

  • You should use loops to input the array and display it:

    int *arr2D[2];
    
    for(int i = 0; i < 2; i++)
        arr2D[i] = new int[6];
    
    for(int i = 0; i < 2; i++)
        for(int j(0); j < 6; j++){
            std::cout << "arr2D[" << i << "][" << j << "]: ";
            std::cin >> arr2D[i][j];
            std::cout << std::endl;
        }
    
    for(int i = 0; i < 2; i++)
        for(int j(0); j < 6; j++){
            std::cout << "arr2D[" << i << "][" << j << "]: "
                << arr2D[i][j] << std::endl;
        }
    

    Finally don't forget to free up memory (Memory allocated with new must be freed up by delete):

    for(i = 0; i < 2; i++)
        delete[] arr2D[i];