title: Correctly deleting a 2D array created in a function
body: <p>I just want to make sure I am understanding this correctly. Although the below function returns a copy of the dynamically allocated pointer to a pointer, since the copy also is bound to the same memory, when I delete the copy the original deletes also.</p>
  
  <p>Similarly the <code>A</code> and <code>B</code> matrices that are passed to the function get passed as copies but since they point to the same memory that one delete at the end will suffice.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "print.h"
  int** square_matrix_multiply(int** A, int** B, int rows)
  {
      int **C;
      C = new int *[rows];
      for(int i = 0; i &lt; rows; i++) {
          C[i] = new int[rows];
          for(int j = 0; j &lt; rows; j++) {
              C[i][j] = 0;
              for(int k = 0; k &lt; rows; k++)
                  C[i][j] += A[i][k]*B[k][j];
          }
      }
      return C;
  }
  int main()
  {
      size_t sz = 6;
      int **A, **B;
      A = new int *[sz];
      B = new int *[sz];
      for(int i = 0; i &lt; sz; i++) {
          A[i] = new int[sz];
          B[i] = new int[sz];
          for(int j = 0; j &lt; sz; j++) {
              A[i][j] = rand() % 100;
              B[i][j] = rand() % 100;
          }
      }
      int** M = square_matrix_multiply(A, B, sz);
      for(int i = 0; i &lt; sz; i++) {
          delete[] A[i];
          delete[] B[i];
          delete[] M[i];
      }
      delete[] A, delete[] B, delete[] M;
      return 0;
  }
  </code></pre>