title: free allocated memory in 2D dynamic memory allocation array in C++
body: <p>I recently posted a question about this, but this is a different question. I created a 2D arrays using dynamic memory allocation, after the matrix is used, we need to free the memory by delete it and I dont understand why we cant just use <code>delete [] matrix</code> to delete it instead of the method in the codes below</p>
  
  <pre><code>int **matrix;
  
      // dynamically allocate an array
      matrix = new int *[row]; 
      for (int count = 0; count &lt; row; count++)
          matrix[count] = new int[col];
  
      // free dynamically allocated memory
      for( int i = 0 ; i &lt; *row ; i++ )
      {
          delete [] matrix[i] ;
          delete [] matrix ;
      }
  </code></pre>
  
  <p>Because the problem is because in <code>main()</code> i created a 2D array and assign the values using other <code>int **</code> functions, i dont know how to delete the allocated memory, the loop will cause runtime error</p>
  
  <pre><code>    int main()
      {
          int **matrixA = 0, **matrixB = 0, **matrixResult = 0; // dynamically allocate an array
          int rowA, colA, rowB, colB; // to hold the sizes of the matrices
  
          // get values for input method
          int inputMethod = userChoiceOfInput();
          if (inputMethod == 1) // select input by keyboard
          {
              cout &lt;&lt; "Matrix A inputting...\n";
              matrixA = getMatricesByKeyboard(&amp;rowA, &amp;colA);
              cout &lt;&lt; "Matrix B inputting...\n";
              matrixB = getMatricesByKeyboard(&amp;rowB, &amp;colB);
          }
          else if (inputMethod == 2) // select input by files
          {
              matrixA = getMatricesByFileInput("F:\\matrixA.txt", &amp;rowA, &amp;colA); 
              matrixB = getMatricesByFileInput("F:\\matrixB.txt", &amp;rowB, &amp;colB); 
          }
  
          //addition(matrixA, &amp;rowA, &amp;colA, matrixB, &amp;rowB, &amp;colB);
  
          cout &lt;&lt; matrixA[1][0];  
  
  ////////////////////////run time error///////////////////////
      // free allocated memory of matrix A
      for( int i = 0 ; i &lt; rowA ; i++ )
      {
          delete [] matrixA[i] ;
          delete [] matrixA ;
      }
      // free allocated memory of matrix B
      for( int i = 0 ; i &lt; rowB ; i++ )
      {
          delete [] matrixB[i] ;
          delete [] matrixB ;
      }
  ////////////////////////run time error///////////////////////
  
          // free allocated memory of matrix A
          delete [] matrixA ; // i dont know what would these delete
          delete [] matrixB ; 
  
          return 0;
      }
  </code></pre>