문제

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];
    }
}
도움이 되었습니까?

해결책 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

다른 팁

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]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top