Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect way of dynamic memory allocation for high-dimensional arrays in C++?
    text
    copied!<p>I was wondering what is the easiest and of course most accurate way for dynamic memory allocation for a 4-D array in C++. What I already know is the following:</p> <pre><code>double**** A; A = new double***[s1]; for (i = 0; i &lt; s1; i++) { A[i] = new double**[s2]; for (j = 0; j &lt; s2; j++) { A[i][j] = new double*[s3]; for (k = 0; k &lt; s3; k++) { A[i][j][k] = new double[s4]; } } } </code></pre> <p>to declare <code>A</code> as a 4-D array of dimensions <code>s1</code>x<code>s2</code>x<code>s3</code>x<code>s4</code>. </p> <p>However, the above is not safe. In the sense that if one of the <code>new</code>s fail to allocate the memory the loops continue without noticing this. </p> <p>To make the above a bit safer, we can enclose it in a <code>try</code>/<code>catch</code> block so that the code does not continue after a <code>bad_alloc</code> has been thrown by <code>new</code> and the code will not try to access some non-existent memory elements and the program can halt at this point.</p> <p>This is OK with the exception that the memory that has already been allocated will not be released before the program finishes. Theoretically with the values of <code>i</code>, <code>j</code>, and <code>k</code> we must be able to precisely say which memory elements are already allocated and release them. But I cannot think of a straightforward way of doing it.</p> <p>For a 2-D case I would do something like this:</p> <pre><code>double** A; try { A = new double*[s1]; } catch(bad_alloc&amp; ba) { delete[] A; throw ba; // or end the program } try { for (i = 0; i &lt; s1; i++) A[i] = new double[s2]; } catch(bad_alloc&amp; ba) { while(--i) { delete[] A[i]; } delete[] A; throw ba; // or end the prog. } </code></pre> <p>The above could be generalized to higher dimensional arrays but I guess it would be very ugly! So I wonder if there is a better way for doing that?</p> <hr> <p>I guess I should also mention that in my case <code>A[i][j][k]</code> is a vector with very few non-zero elements. Hence, I only take <code>s3</code> to be as big as the number of non-zero elements (and then take care of mapping indices and ... later). <code>s3</code>, however, depends on <code>j</code>. That's why using the traditional memory allocation is easier than higher-level APIs like <code>vector</code></p>
 

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