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:49

>>13
Well since a is a local variable in the function ptrX and its closely named friends won't share values with arr.

If you're not using the variable just drop it.

#include <stddef.h> /* size_t */

void allocate (size_t n, int ** x, int *** y, int **** z) {
  *x = new int[n];
  *y = x;
  *z = y;
}

int main(void) {
  int * ptrX, ** ptrY, *** ptrZ;

  allocate(5, &ptrX, &ptrY, &ptrZ);

  delete [] ptrX;
  return 0;
}


Again this is untested and I don't really know C++ but I think it should work.

I would encourage you never to design functions that allocate things you have to deallocate on another level, if you must at least provide an explicit reminder in the function documentation and a corresponding deallocate/free/close function.

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