Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The question is tagged C++, and yet the answers only use the C subset...</p> <p>Well, first of all, I would recommend against the whole thing. Create a class that encapsulates your matrix and allocate it in a single block, offer <code>operator()(int,int)</code> to gain access to the elements...</p> <p>But back to the problem. In C++ you should use references rather than pointers to allow the function to change the argument, so your original allocate signature should be:</p> <pre><code>void AllocMat(int **&amp;mat, int size); </code></pre> <p>And call it like:</p> <pre><code>int **matrix = 0; AllocMat( matrix, 5 ); </code></pre> <p>Or better, just <em>return</em> the pointer:</p> <pre><code>int **AllocMat( int size ); int **matrix = AllocMat( 5 ); </code></pre> <p>For the deallocation function, since you don't need to modify the outer pointer, you can just use:</p> <pre><code>void DeallocMat( int**mat, int size ); // size might be required to release the // internal pointers </code></pre> <p>Now, for a sketch of the C++ solution:</p> <pre><code>template &lt;typename T&gt; // no need to limit this to int class square_matrix { const unsigned size; T * data; public: square_matrix( unsigned size ) : size(size), data( new T[size*size]() ) {} square_matrix( matrix const &amp; m ) : size( m.size ), data( new T[m.size*m.size] ) { std::copy( m.data, m.data+size*size, data ); } ~matrix() { delete [] data; } T const &amp; operator()( unsigned x, unsigned y ) const { // optional range check and throw exception return data[ x + y*size ]; } void set( unsigned x, unsigned y, T const &amp; value ) { // optional range check and throw exception data[ x + y*size ] = value; } }; </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