lundi 5 avril 2021

Problem while creating 2D array dynamically in C++. Here is the code. It dosen't work for some specific conditions

In my following code i am taking input (int) rows and cols form the user and creating a 2d array. After taking the input i am printing the same 2d array.

#include<iostream>
using namespace std;
int main()
{
    int rows,cols;
    cin>>rows>>cols;
    int **matrix=new int*[cols];
    for(int j=0;j<cols;j++)
    {
        matrix[j]=new int[rows] ;
    }
    for(int j=0;j<rows;j++)
    {
        for(int k=0;k<cols;k++)
        {
            cin>>matrix[j][k];
        }
    }
    for(int j=0;j<rows;j++)
    {
        for(int k=0;k<cols;k++)
        {
            cout<<matrix[j][k]<<" ";
        }
        cout<<endl;
    }
}

The above code works perfectly in 2 cases:

1st. when input rows and cols are equal.
2nd. when cols>rows.

It dosent work for the case in which rows>cols. If you don't trust me, run it and check. I don't know where i am going wrong. Compiler is also not giving any errors. Please help!!

Aucun commentaire:

Enregistrer un commentaire