Sunday, August 29, 2010

C++: Passing a pointer as a reference!

It is trivia that when you send an array as a parameter to a function, its pass by reference instead of C++ pass by value default to any other object. But sometimes, there is a need when you want to pass an uninitialized array, hence making it a pointer. A pointer that is treated as an array must be allocated before use. And allocating an array means creating a brand new pointer. So the pointer you sent before is no longer pointing to the same address. This is how to pass a pointer and yet preserving its address.

 
So here is the case: you want to send a blank array to a function. but you dont know the size of the array before you get into the function. So basically you want to send a pointer, let name it result. Inside the function, you want to allocate the size of this pointer, hence it becomes an array. You allocate the array by calling malloc() function, eg:

result = (int*)malloc(3);

and inside the function you fill the array, eg:

result[0] = 1;
result[1] = 6;
result[2] = 7;

so your function would be:

void testArray(int* result) { 
 result = (int*)malloc(3);
assert(result);
(result)[0] = 1;
(result)[1] = 6;
(result)[2] = 7;
}

if you try to print the result after you called this function, you wont get 1, 6, 7. You will get a random value. Why is that? Isn't sending a pointer is a pass by reference? Well apparently not always.

When you call result = (int*)malloc(3), it makes a brand new array, which points to a different value. So the adress you sent previously is replaced by a new address (the result of malloc() function, click here for detail on this function). So the adress you sent to the function is being replace to a new address of the value. But back in the main class, result still pointing to the old address, so basically its pointing to something else.

So how to actually send a pointer as a reference. Its easy: send a pointer of the pointer. Sounds crazy huh? But its pretty simple. All you have to do is to change the function like this:

void testArray(int** array) {
*array = (int*)malloc(3);
assert(*array);
(*array)[0] = 1;
(*array)[1] = 6;
(*array)[2] = 7;
}

int main ()
{
int * array;
testArray(&array);
}

Its a working program so you can test it directly. Since malloc replace the address of an address, it does not replace the original address(the same rule to new commands too). Simple huh?

No comments: