Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The thing that confuses me about your question is that most people would not declare a matrix as an <code>int **</code>. The reason for this is that you would be forced to then allocate it in a loop. Your allocation function would require two parameters, which are the dimensions of the array like this:</p> <pre><code>void AllocMat(int *** mat, int n, int m) { int ** result = new int * [ n ]; for (int x=0; x&lt;n; x++) { result[x] = new int [ m ]; } *mat = result; } </code></pre> <p>If this were the case, the corresponding deallocation function would require knowledge of the size of n as follows:</p> <pre><code>void DeallocMat(int *** mat, int n) { if (mat == NULL || *mat == NULL) return; int ** tmp = *mat; for (int x=0; x&lt;n; x++) { if (tmp[x] != NULL) delete [] tmp[x]; } delete [] tmp; *mat = NULL; } </code></pre> <p>With this approach, you could access your matrix like this:</p> <pre><code>int ** mat = NULL; AllocMat(&amp;mat, n, m); for (int x=0; x&lt;n; x++) { for (int y=0; y&lt;m; y++) { mat[x][y] = 1; } } DeallocMat(&amp;mat, n); </code></pre> <p>Usually, people allocate matrices as a single buffer of memory to avoid extra allocations and pointer indirections, which is how I recommend you do it. In that case, you allocation function would look like this:</p> <pre><code>void AllocMat2(int ** mat, int n, int m) { *mat = new int [ n * m ]; } </code></pre> <p>And the corresponding deallocation function like this:</p> <pre><code>void DeallocMat2(int ** mat) { if (mat != NULL &amp;&amp; *mat != NULL) { delete [] *mat; *mat = NULL; } } </code></pre> <p>And you would access it follows:</p> <pre><code>int * mat2 = NULL; AllocMat2(&amp;mat2, n, m); for (int x=0; x&lt;n; x++) { for (int y=0; y&lt;m; y++) { mat2[x * n + y] = 1; } } DeallocMat2(&amp;mat2); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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