Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are using C.99, you can use a variable length array (VLA) to dynamically allocate your 3-dimensional array. Once <code>side</code> is determined, you can declare your pointer to be:</p> <pre><code>char (*cube3d_)[side][side]; </code></pre> <p>And then initialize it like this:</p> <pre><code>cube3d_ = malloc(side * sizeof(*cube3d_)); </code></pre> <p>Note that in C, you are not required to cast the return value of <code>malloc()</code>, and doing so can actually lead to undefined behavior in the worst case. Since the "cube" has been allocated as a contiguous block, it can be copied with <code>memcpy()</code>.</p> <p>C++ does not have VLA. You can use a <code>vector</code> to get the C++ equivalent of your multi-dynamic allocation structure:</p> <pre><code>std::vector&lt;std::vector&lt;std::vector&lt;char&gt; &gt; &gt; cube3d_(side, std::vector&lt;std::vector&lt;char&gt; &gt;(side, std::vector&lt;char&gt;(side))); </code></pre> <p>You can then copy it using a copy constructor or an assignment.</p> <hr> <p>If <code>cube3d_</code> is a member variable of an object/structure, so long as your object knows the value of <code>side</code>, you can still use a VLA pointer to access the memory. For example:</p> <pre><code>struct Obj { size_t side_; void *cube3d_; }; //... size_t side = 3; //... Obj o; o.side_ = side; char (*p)[o.side_][o.side_] = malloc(o.side_ * sizeof(*p)); o.cube3d_ = p; //... char (*q)[o.side_][o.side_] = o.cube3d_; q[1][2][2] = 'a'; </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