Dynamic Memory Allocation of Vectors in C++
<p>I need to write a function that adds the elements of two 3D arrays, stores the result in a third 3D array, takes the results and copies them into a one dimensional vector, then returns this vector by constant reference. The problem I am having is how to use dynamic memory allocation to return the vector since you cannot return a local variable. This is what the code looks like if you COULD return a local variable:</p>

<pre><code>template &lt;class T&gt;
const vector&lt;T&gt;&amp; allOperations(T*** const &amp;x, T*** const &amp;y, T*** &amp;z, int height, int width, int depth)
{
    vector&lt;T&gt; results(height*width*depth);

    // Add the values of array x and y
    for (int i = 0; i &lt; height; i++)
    {
        for (int j = 0; j &lt; width; j++)
        {
            for (int k = 0; k &lt; depth; k++)
            {
                z[i][j][k] = x[i][j][k] + y[i][j][k];
            }
        }
    }

    int l = 0;
    //Places the values of array z into a vector 
    for (int i = 0; i &lt; height; i++)
    {
        for (int j = 0; j &lt; width; j++)
        {
            for (int k = 0; k &lt; depth; k++)
            {
                results[l] = z[i][j][k];
                l++;
            }
        }
    }
    return results;
}
</code></pre>

<p>Here is my incorrect attempt at using dynamic memory allocation:</p>

<pre><code>template &lt;class T&gt;
const vector&lt;T&gt;&amp; allOperations(T*** const &amp;x, T*** const &amp;y, T*** &amp;z, int height, int width, int depth)
{
    vector&lt;T&gt;* results(height*width*depth) = new vector&lt;T&gt;;

    // Add the values of array x and y
    for (int i = 0; i &lt; height; i++)
    {
        for (int j = 0; j &lt; width; j++)
        {
            for (int k = 0; k &lt; depth; k++)
            {
                z[i][j][k] = x[i][j][k] + y[i][j][k];
            }
        }
    }

    int l = 0;
    //Places the values of array z into a vector 
    for (int i = 0; i &lt; height; i++)
    {
        for (int j = 0; j &lt; width; j++)
        {
            for (int k = 0; k &lt; depth; k++)
            {
                *results[l] = z[i][j][k];
                l++;
            }
        }
    }
    return *results;
}
</code></pre>
