title: Way to ensure a dynamically allocated matrix is square?
body: <p>I would like to determine if there is a way to determine whether a dynamically allocated matrix is square (nxn). </p>
  
  <p>The first thing that came to mind was to see if there is a way to find out whether a pointer is about to point to an invalid memory location. But according to these posts:</p>
  
  <p><a href="https://stackoverflow.com/questions/17202570/c-is-it-possible-to-determine-whether-a-pointer-points-to-a-valid-object?noredirect=1&amp;lq=1">C++ Is it possible to determine whether a pointer points to a valid object?</a></p>
  
  <p><a href="https://stackoverflow.com/questions/551069/testing-pointers-for-validity-c-c">Testing pointers for validity (C/C++)</a></p>
  
  <p>This cannot be done. </p>
  
  <p>The next idea I came up with was to somehow use the sizeof() function to find a pattern with square matrices, but using sizeof() on a pointer will always yield the same value. </p>
  
  <p>I start off by creating a dynamically allocated array to be of size <em>nxn</em>:</p>
  
  <pre><code>int **array = new int*[n]
  for(int i = 0; i &lt; n; i++)
      array[i] = new int[n];
  
  for(int i = 0; i &lt; n; i++){
      for(int j = 0; j &lt; n; j++){
          array[i][j] = 0;
      }
  }
  </code></pre>
  
  <p>Now I have a populated square matrix of size <em>nxn</em>. Let's say I'm implementing a function to print a square 2D array, but a user has inadvertently created and passed a 2D array of size <em>mxn</em> into my function (accomplished by the code above, except there are more row pointers than elements that comprise the columns, or vice versa), and we're also not sure whether the user has passed a value of <em>n</em> corresponding to <em>n</em> rows or <em>n</em> columns:</p>
  
  <pre><code>bool(int **arr, int n){
      for(int rows = 0; rows &lt; n; rows++)
          for(int cols = 0; cols &lt; n; cols++)
              cout &lt;&lt; *(*(arr + rows) + cols) &lt;&lt; " ";
              // Is our next column value encroaching on unallocated memory?  
          }
          cout &lt;&lt; endl;
          // Is our next row value out of bounds?
      }
  }
  </code></pre>
  
  <p>Is there any way to inform this user (before exiting with a segmentation fault), that this function is for printing square 2D arrays only?</p>
  
  <p>Edit: corrected 3rd line from</p>
  
  <pre><code>array[i] = new int[i]
  </code></pre>
  
  <p>to</p>
  
  <pre><code>array[i] = new int[n]
  </code></pre>