Printing values from a pointer to an array returned from a function (C++)
<p>I have a function that returns a pointer to an array, and I want to print each value in the array</p>

<p>When I run it, it prints</p>

<pre><code>int* merge_sort(int arr[], int size) {
    if (size &lt;= 1) {
        return &amp;arr[0];
    }

    int size1 = size/2;
    int arr1[size1];
    for (int i = 0; i &lt; size1; i++) {
        arr1[i] = arr[i];
    }

    int size2 = size-size1;
    int arr2[size2];
    for (int i = 0; i &lt; (size2); i++) {
        arr2[i] = arr[i+size1];
    }

    int p1 = 0;
    int p2 = 0;
    int sorted[size];

    while (p1 &lt; size1 &amp;&amp; p2 &lt; size2) {
        if (arr1[p1] &lt; arr2[p2]) {
            sorted[p1+p2] = arr1[p1];
            p1++;
        } else {
            sorted[p1+p2] = arr2[p2];
            p2++; 
        }
    }

    while (p1 &lt; size1) {
        sorted[p1+p2] = arr1[p1];
        p1++;
    }

    while (p2 &lt; size2) {
        sorted[p1+p2] = arr2[p2];
        p2++;
    }

    cerr &lt;&lt; "sorted: ";
    for (int&amp; i : sorted) {
        cerr &lt;&lt; i &lt;&lt; ",";
    }
    cerr &lt;&lt; endl;

    return &amp;sorted[0];
} 

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
int main()
{
    int N;
    int horses[N];

    cin &gt;&gt; N; cin.ignore();
    for (int i = 0; i &lt; N; i++) {
        int Pi;
        cin &gt;&gt; Pi; cin.ignore();
        horses[i] = Pi;
    }

    int *sorted = merge_sort(horses, N);

    cerr &lt;&lt; "~ " &lt;&lt; sorted[0] &lt;&lt; " " &lt;&lt; sorted[1] &lt;&lt; " " &lt;&lt; sorted[2] &lt;&lt; endl;

    //cerr &lt;&lt; "~~ " &lt;&lt; sorted &lt;&lt; " " &lt;&lt; *sorted &lt;&lt; " " &lt;&lt; endl;

    cerr &lt;&lt; "^ " &lt;&lt; *(sorted + 0) &lt;&lt; endl;
    cerr &lt;&lt; "^ " &lt;&lt; *(sorted + 1) &lt;&lt; endl;
    cerr &lt;&lt; "^ " &lt;&lt; *(sorted + 2) &lt;&lt; endl;

    for (int i = 0; i &lt; N; i++) {
        //cerr &lt;&lt; "i " &lt;&lt; i &lt;&lt; endl;
        // cerr &lt;&lt; "SORTED?? " &lt;&lt; sorted[i] &lt;&lt; endl;
        cerr &lt;&lt; "value: " &lt;&lt; *(sorted + i) &lt;&lt; " ";
        //cerr &lt;&lt; "*** " &lt;&lt; *(sorted) + i &lt;&lt; endl;

    }
    cerr &lt;&lt; endl;
}
</code></pre>

<p>When I run it, it prints</p>

<p>sorted: 5,8,9,
~ 5 8 9
^ -5728
^ 942815029
^ 6297320
value: 959592096 value: 0 value: -157570874</p>

<p>Why is my for loop not printing the values "5, 8, 9"? How can I fix it so that it does?</p>

<p>(Edited to be more detailed. Also, I realize my merge sort is wrong but I'm just trying to get it to return something I can use right now ^.^)</p>