Note that there are some explanatory texts on larger screens.

plurals
  1. POTwo dimensional arrays allocation problem
    text
    copied!<p>this is an interview question my friend was asked yesterday. The question was something like: will this program crash with an "access violation" error or not? I looked at it for a while and thought no, it won't. But actually trying this out in visual studio proved me wrong. I cannot figure out what happens here... or to be more precise, i know what happens, but do not understand WHY. The problem seems to be that the matrix2 array does not get allocated at all.</p> <p>Code below:</p> <pre><code>#include &lt;iostream&gt; #include &lt;ctime&gt; using namespace std; int** matrixAlloc( const int rows, const int cols ); void matrixAlloc( int** matrix, const int rows, const int cols ); void matrixDealloc( int** m, const int rows); void matrixPrint( const int* const * const m, const int rows, const int cols ); int main( int argc, char** argv ) { srand( (unsigned int)time( NULL ) ); int** matrix1 = matrixAlloc( 4, 5 ); matrixPrint( matrix1, 4, 5 ); matrixDealloc( matrix1, 4 ); int ** matrix2 = NULL; matrixAlloc( matrix2, 4, 5 ); matrixDealloc( matrix2, 4 ); // &lt;--- crash occurs here } int** matrixAlloc( const int rows, const int cols ) { int **matrix = new int *[ rows ]; for ( int i = 0; i &lt; rows; i++ ) { matrix[ i ] = new int[ cols ]; for ( int j = 0; j &lt; cols; j++ ) { matrix[ i ][ j ] = (rand() * 12347) % 10; } } return matrix; } void matrixAlloc( int** matrix, const int rows, const int cols ) { matrix = new int *[ rows ]; for ( int i = 0; i &lt; rows; i++ ) { matrix[ i ] = new int[ cols ]; for ( int j = 0; j &lt; cols; j++ ) { matrix[ i ][ j ] = (rand() * 12347) % 10; } } } void matrixDealloc( int** matrix, const int rows ) { for ( int i = 0; i &lt; rows; i++ ) { delete [] matrix[ i ]; } delete [] matrix; } void matrixPrint( const int* const * const matrix, const int rows, const int cols ) { for ( int i = 0; i &lt; rows; i++ ) { for ( int j = 0; j &lt; cols; j++ ) { cout &lt;&lt; matrix[ i ][ j ] &lt;&lt; " "; } cout &lt;&lt; endl; } cout &lt;&lt; endl; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload