Quote:
it looks like we are giving space for an 1-D array then changing it to a 2-D array, that's why it look odd to me.
Consider this allocator function:
(Im using char* for my illustration rather than void* since it is impossible to allocate void chunks)
void Alloc(char* ptr, int size){ ptr = new char[size];}char *my_cstring;Alloc(my_cstring, 32);
Now this will not work, and it results in a memory leak.
Im not sure how to explain what happens here very well, but the way I see it, the compiler makes a copy of the ptr argument, and then that copy is allocated to the new memory. Obviously a disaster...
To make it work we can do like this:
void Alloc(char** ptr, int size){ *ptr = new char[size];}char *my_cstring;Alloc(&my_cstring, 32);
Now this will work, and it does not result in a memory leak.
The way I see it, ptr is a pointer to the pointer that is to be allocated memory. The complier does basically the same as before, but
this time a copy is made of the pointer that points to the actual pointer I want to allocate memory to. This solves the problem from the first example. I guess you can say that we play a little trick on the compiler so that it doesnt make a copy of the actual pointer.
Ofcourse, as long as the function doesnt change what the pointer points to, this conversion from * to ** is not necessary.
The price we pay for this little trick is a pretty nasty and non-intuitive syntax. Only God knows why MS dont use C++ references for this kind of thing.
It looks like the old boys is going to make the rules for another few years.
As you mentioned earlier, why not do this:
char **my_cstring;Alloc(my_cstring, 32);
The compiler will probably accept this scenario, but the problem is that char** was not what I wanted. It is not the same as char*, and it can not be fed to printf or something similar.
[Edited by - pulpfist on May 19, 2006 11:17:43 PM]