Question

I have the following code, I made sure I did everything as explained in Pointer-to-pointer dynamic two-dimensional array

I need my 2d matrix to be dyanmic i.e the user needs to enter the dimensions. But I am getting error in my cin when taking the input form the user. whats wrong with the following code?

int numberOfRows, numberOfColumn;
cout << "Please enter the number of rows: ";
cin >> numberOfRows;
cout << endl << "Please enter the number of columns ";
cin >> numberOfColumn;


int** matrix= new int*[numberOfRows];

for (int i=0; i<numberOfRows; i++)
{
    matrix[numberOfRows]= new int[numberOfColumn];
}

for (int i=0; i<numberOfRows; i++)
{
    for(int j=0; j<numberOfColumn; j++)
    {
        cout << "Please enter Row " << (i+1) << " Column "<< (j+1) <<" element: ";
        cin>> matrix[i][j];
        cout << endl;
    }
}

for (int i=0; i<numberOfRows; i++)
{

    for(int j=0; j<numberOfColumn; j++)
    {
        cout << matrix[i][j];
    }
}
Was it helpful?

Solution 2

While allocating memory in for loop

matrix[i]= new int[numberOfColumn]; 
     instead of matrix[numberOfRows]= new int[numberOfColumn];

Note:you also need to free the allocated memory

corrected code

http://ideone.com/ILw1qa

OTHER TIPS

You have this:

  for (int i=0; i<numberOfRows; i++)
  {
      matrix[numberOfRows]= new int[numberOfColumn];
  }

Should be:

  for (int i=0; i<numberOfRows; i++)
  {
      matrix[i]= new int[numberOfColumn];
  }

Notice that the matrix[numberOfRows] changed to matrix[i]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top