Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

[C++] Allocating local variables

Name: Anonymous 2012-09-02 0:12

Shouldn't this be working? I'm trying to point all three pointers to this new int array, but the address isn't right.

<code>void allocate(int a[], int * &x, int ** &y, int *** &z)
{
    a = new int [ 5 ];

    x = a;
    y = new int*;
    *y = a;
    z = new int**;
    *z = new int*;
    **z = a;

    return;
}

int main()
{
    int arr[5];

    int *ptrX;
    int **ptrY;
    int ***ptrZ;

    // Allocate the dynamic memory
    allocate(arr, ptrX, ptrY, ptrZ);

    return 0;
}</code>

Name: Anonymous 2012-09-02 16:30

>>31
Different poster here, but I'm not sure that 2nd code snippet would work. Might throw an error. Even if it doesn't though, it's doing something different than the first. It's allocating two different arrays; an array with 5 integers on the stack, and an array with 4 integers on the heap.

But this:

int a[5] = {1, 2, 3, 4, 5};

should be equivalent to this:

int *b;
b = new int[5];


except b would be on the heap. You could reference both the same way though. Array notation (b[3]) or pointer notation (*(a + 3)).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List