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 17:08

>>38
Runs okay for me.

arr = 0023FE94, &arr = 0023FE94
b = 003330F0, &b = 0023FE88

Press any key to continue . . .


If you're referring to b and &b being different addresses, that's because the address being ointed to is different the actual address of the pointer variable. The array name (arr) is a constant pointer, but its address is the same as the address of the first array element it points to because it can't ever be changed.

You could also add this:

#include <cstdio>

int main(int argc, char** argv) {

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

  printf("arr = %p, &arr = %p, &arr[0] = %p\n", arr, &arr, &arr[0]);
  printf("b = %p, &b = %p\n", b, &b);

  delete[] b;
  return 0;
}


and see how arr, &arr and &arr[0] are really synonymous.

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