Need of Pointer to pointer
What is necessary for storing the address of a pointer?
int a = 2;
int *p = &a;
int **q = &p;
Any practical use? Real time applications.
In C you can either pass "value" or "address" of an object. If you pass value in function call, then changes made in the function don't reflect at calling place. And to reflect changes, you need to pass address of the object, for example:
void insert(node* head){
head->data = 10; // address(or head) is still same
}
By object I means any type int, char or struct e.g. node
In the above example you change value at addressed by head
pointer and change in data
will be reflected.
But suppose if you want to change head
itself in your list (e.g. insert new node as first node).
void insert(node* head){
head = malloc(sizeof(head)); // head changed
head->data = 10;
}
Then value doesn't reflect at calling place because this head
in function is not the same as head
at calling place.
You have two choice, either return head
or use pointer to pointer
(but remember only one value can be return).
Use pointer to pointer:
void insert(node** head){
(*head) = malloc(sizeof **head);
(*head)->data = 10;
}
Now changes will reflect!
The point is, if address is your value (need to updated address), then you need to use pointer of address or I should say pointer to pointer to reflect changes at the calling place.
As your question is what is need of pointer to pointers, one more place where pointer to pointer used in array of string, and dynamic 2-D arrays, and for same use you may need pointer to pointer to pointer for example dynamic matrix of String or/ 3D char array.
Read also this:Pointers to Pointers I just found, to tell you for an example.
A **
is just a pointer to a pointer. So where an *p
contains the address of an p
, p**
contains the address of an p*
that contains the address of an p
object.
**
is used when you want to preserve the Memory-Allocation or Assignment even outside of a function call.
Also check this article.
EXAMPLE:-
void allocate(int** p)
{
*p = (int*)malloc(sizeof(int));
}
int main()
{
int* p = NULL;
allocate(&p);
*p = 1;
free(p);
}
Does
int main (int argc, char** argv) { ... }
Look familiar?
If you want to allocate Nth order pointer in other function, you should use (N+1)th order pointer. For example:
void allocate_matrix(int ***ptr, int x, int y);
Lets us allocate a matrix:
int **matrix:
allocate_matrix(&matrix, 5, 5);
One use for this is to change the value of a pointer from within a function. For example:
#include <stdio.h>
void swapStrings(const char **strA, const char **strB)
{
const char *tmp = *strB;
*strB = *strA;
*strA = tmp;
}
int main()
{
const char *a;
const char *b;
a = "hello";
b = "world";
swapStrings(&a,&b);
// now b points to "hello" and a points to "world"
printf("%s\n", a);
printf("%s\n", b);
}
Outputs:
world
hello