Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>2D C-style arrays in C and C++ are a block of memory of size <code>rows * columns * sizeof(datatype)</code> bytes.</p> <p>The actual [row][column] dimensions exist only statically at compile time. There's nothing there dynamically at runtime!</p> <p>So, as others have mentioned, you can implement</p> <pre><code> int array [ rows ] [ columns ]; </code></pre> <p>As:</p> <pre><code> int array [ rows * columns ] </code></pre> <p>Or as:</p> <pre><code> int * array = malloc ( rows * columns * sizeof(int) ); </code></pre> <hr> <p>Next: Declaring a variably sized array. <strong>In C</strong> this is possible:</p> <pre><code>int main( int argc, char ** argv ) { assert( argc &gt; 2 ); int rows = atoi( argv[1] ); int columns = atoi( argv[2] ); assert(rows &gt; 0 &amp;&amp; columns &gt; 0); int data [ rows ] [ columns ]; // Yes, legal! memset( &amp;data, 0, sizeof(data) ); print( rows, columns, data ); manipulate( rows, columns, data ); print( rows, columns, data ); } </code></pre> <hr> <p><strong>In C</strong> you can just pass the variably-sized array around the same as a non-variably-sized array:</p> <pre><code>void manipulate( int theRows, int theColumns, int theData[theRows][theColumns] ) { for ( int r = 0; r &lt; theRows; r ++ ) for ( int c = 0; c &lt; theColumns; c ++ ) theData[r][c] = r*10 + c; } </code></pre> <p><strong>However, in C++</strong> that is not possible. You need to allocate the array using dynamic allocation, e.g.: </p> <pre><code>int *array = new int[rows * cols](); </code></pre> <p>or preferably (with automated memory management)</p> <pre><code>std::vector&lt;int&gt; array(rows * cols); </code></pre> <p>Then the functions must be modified to accept 1-dimensional data:</p> <pre><code>void manipulate( int theRows, int theColumns, int *theData ) { for ( int r = 0; r &lt; theRows; r ++ ) for ( int c = 0; c &lt; theColumns; c ++ ) theData[r * theColumns + c] = r*10 + c; } </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