Search code examples
c++arrayspointersuser-inputnew-operator

2D integer array in c++ with uneven number of elements in each row


The number of rows and columns of this array are given by the user however the number of rows are not the same (the array is uneven) and also the user will fill the array by entering the elements.

This is the code that I wrote but when I try to take input from user, the code crashes after taking some inputs. Please could you help me out and correct my code and point my flaws. Thank you.

#include <iostream>
//2d array
using namespace std;

int main()
{
    int row;
    int col_x;
    cout << "Enter the row number:" << endl;
    cin >> row;
    //cout<<"Enter the column number:"<<endl;
    //cin>>col;
    int **a = new int *[row];
    for (int r = 0; r < row; r++)
    {
        cout << "Enter the column no.of array " << r << endl;
        cin >> col_x;
        a[r] = new int[col_x];

        cout << "Enter the elements in the array:" << endl;
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col_x; j++)
            {
                cin >> a[i][j];
            }
        }
        cout << "The elements in the array:" << endl;
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col_x; j++)
            {
                cout << a[i][j] << " ";
            }
            cout << endl;
        }
    }

    delete[] a;
    a = NULL;

    return 0;
}

Solution

  • There was an extra for loop. Also, you have to store the size of each row. And make the proper deallocation of the 2D array.

    #include <iostream>
    //2d array
    using namespace std;
    
    int main()
    {
        int row;
        cout<<"Enter the row number:"<<endl;
        cin>>row;
        int **a=new int *[row];
        int *col_x = new int [row];
    
        for(int r=0;r<row;r++){
            cout<<"Enter the column no.of array "<<r<<endl;
            cin>>col_x[r];
            a[r]=new int[col_x[r]];
    
            cout<<"Enter the elements in the array:"<<endl;
    
            for(int j=0;j<col_x[r];j++){
                cin>>a[r][j];
            }
        }
    
        cout<<"The elements in the array:"<<endl;
         for(int i=0;i<row;i++){
            for(int j=0;j<col_x[i];j++){
                cout<<a[i][j]<<" ";
            }
            cout<<endl;
        }
    
        for (int i=0; i<row; ++i)
            delete[] a[i];
        delete []a;
        delete []col_x;
        return 0;
    }