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 1:38

>>6
When you wrote int arr[5]; then you have already allocated an array of five ints.

When you type int a[] in the function this gets interpreted as int *a which is a local variable.

Unless you are mandated to use the heap you should avoid in this case entirely.

void set_ptrs (int * storage, int ** x, int *** y, int **** z) {
  *x = storage;
  *y = x;
  *z = y;
}

int main(void) {
  int arr[5];
  int * ptrX, ** ptrY, *** ptrZ;

  set_ptrs(arr, &ptrX, &ptrY, &ptrZ);

  return 0;
}


I have not tested this code but I am confident that it will do what you wish.

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