Astaboom Astaboom - 5 days ago 6
C++ Question

confusion with passing arrays by reference using pointers

I just asked a question several hours ago, and I have been utterly confused with something pointed out in the answers (arrays using pointers in c++: segmentation fault when accessing the returned array). Some people have been responding a bit negatively to my newb questions, so I went over my book about pointers, which did not help me much. So, here I go again.

In the previous question, I had a function

void builder(int aSize1, int aSize2, int aSize3, int*** frequencies)
that I thought would dynamically allocate memory for the 3d array passed in for the
int*** frequencies
parameter and initialize it. However, I was told that only a copy would be passed into the function and I would be allocating and initializing just for the copy not the original. Hence, they have advised me to use a reference instead, rendering the function prototype as
void builder(int aSize1, int aSize2, int aSize3, int***& frequencies)
.

However, I recalled that just yesterday when I first stumbled upon this concept of pass by reference using pointers, one would be able to manipulate the data of the pointer as well. To wit,

void change_what_this_points_to( int* a )
{
*a = 42;
}


this function does change the value of a pointer that is fed into the function.

So, my question is, why does the former pass in a copy while the latter passes the real deal? I do not see much difference between the two functions, aside from the fact that one has more asterisks.

Any help would be appreciated. Thanks!

Answer

This function

void change_what_this_points_to( int* a )
{
    *a = 42;
}

does not change the pointer itself. It changes the integer object pointed to by the pointer.

If you want to change the pointer itself you should write the function either the following way

void change_what_this_points_to( int * &a )
{
    a = new int( 42 );
}

or the following way

void change_what_this_points_to( int **a )
{
    *a = new int( 42 );
}

Thus returning to your function you should declare it either like

void builder(int aSize1, int aSize2, int aSize3, int*** &frequencies);

or like

void builder(int aSize1, int aSize2, int aSize3, int**** frequencies);
Comments