Reputation: 379
What is the point passing the address of a pointer as a parameter? For example:
int *ptr_one;
ptr_one = (int *)malloc(sizeof(int));
then function is being called as the following:
func(&ptr_one);
Note the function argument is as follow:
func(int **ptr)
{
......
}
Upvotes: 1
Views: 504
Reputation: 4203
If you wish to modify the pointer itself, then you need to pass it either by reference, or by the address of the pointer. E.g.,
func(int **ptr)
{
free(ptr);
ptr = new int[2]; //side note: use new instead of malloc in C++
//memory allocated with new is deallocated with
//delete
}
In C, passing the address of a pointer was the only way you could allocate or deallocate the memory of that pointer in a function. In C++, however, it is usually better to pass by reference instead. So a C++ version of your code would look like:
int *ptr = new int;
func(ptr);
delete ptr;
void func(int *&ptr) {
.
.
.
}
Upvotes: 2
Reputation: 57749
The purpose of passing a pointer to a pointer is so that the pointer variable can be modified.
Recall, from the C-style of coding, that a parameter can be modified by passing the address or pointer to the parameter. If the parameter is an int that needs to be modified, a pointer to the integer is passed. Likewise, if a pointer parameter will be modified by the function, it was passed by pointer to pointer (or address of pointer).
Upvotes: 2