2

In my project, there is a definition of a function call like this.

    int32 Map(void * &pMemoryPointer)

In the calling place, the paramenter passed is void*, why cant we just receive it as a pointer itself, instead of this?

Saran-san
  • 361
  • 3
  • 14

3 Answers3

6

Without knowing what the Map function does, I'd guess that it sets the pointer. Therefore it has to be passed by reference.


Using a reference to a pointer, you can allocate memory and assign it to the pointer inside the function. For example

void DoSomething(int*& pointerReference)
{
    // Do some stuff...

    pointerReference = new int[someSize];

    // Do some other stuff...
}

The other way to make functions like that is to return the pointer, but as the Map function in the question returns something else that can't be used.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
4

Reading it backwards, this means that pMemoryPointer is a reference (&) to a pointer (*) to void. This means that whatever pointer you pass gets referenced, and any modification that the function will do to pMemoryPointer will also affect the original (passed) pointer (e.g. changing the value of pMemoryPointer will also change the value of the original pointer).

why cant we just receive it as a pointer itself, instead of this?

That's because by doing that, you are copying the pointer and any change that you'll make to the copy doesn't reflect to the original one.

void im_supposed_to_modify_a_pointer(void* ptr) {  // Oh no!
   ptr = 0xBADF00D;
}

int* my_ptr = 0xD0GF00D;
im_supposed_to_modify_a_pointer(my_ptr);
ASSERT(my_ptr == 0xBADF00D) // FAIL!
Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
0

That's a weird function prototype IMHO, but it means (Update) that the Map function accepts a reference to a void pointer as a parameter.

So I think, it is equivalent to declaring the function like this:

 int32 Map(void** pMemoryPointer)
Rami
  • 7,162
  • 1
  • 22
  • 19
  • it is only "equivalent" if pointers and references were equivalent – newacct Oct 25 '13 at 00:36
  • @newacct: that's right. Adding that useful link here: http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c – Rami Oct 25 '13 at 00:44