0

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];
    }
}
Community
  • 1
  • 1
Purpamine
  • 141
  • 2
  • 14

2 Answers2

2

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]

joseph
  • 2,429
  • 1
  • 22
  • 43
  • It always helps to get a second pair of eyes on something when you get stuck. I'm glad I could help. – joseph Feb 08 '14 at 20:09
1

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

shivakumar
  • 3,297
  • 19
  • 28
  • Yes I will free the allocated memory. I cannot believe that I made just a crappy mistake. Thank you much, I would have never seen that. – Purpamine Feb 08 '14 at 20:06
  • To free the allocated memory do I just delete [] matrix or do I need to do a loop and delete very int* pointed by matrix then delete matrix itself? – Purpamine Feb 08 '14 at 20:33