int *p1;
int **p2;
Although I know the difference of the meaning between pointer p1 and pointer p2 , in practice I wonder in what cases pointer like p2 should be used instead of p1.
Bichi
int *p1;
int **p2;
Although I know the difference of the meaning between pointer p1 and pointer p2 , in practice I wonder in what cases pointer like p2 should be used instead of p1.
Bichi
p2 is a pointer to a pointer. It's used a lot in COM programming and DirectX but it can also be used when you need to maintain a complex list of structures, objects, or more importantly pointers to functions and interfaces. I try not to use it too much because it can become confusing even for an experience coder. The advantage to storing structures and objects this way is that it is easy to remove, add, sort and use them.
And I never do this:
int ***p2;
Because thinking about a pointer to a pointer to a pointer gives me a headache.
The advantage of a pointer to a pointer as it relates to functions and interfaces is that if you change the name of the function, you simply have to change what function the pointer points to, rather than rewrite your code every time you call that function. So instead of calling a function you call its interface, which in turn calls the function via a pointer. So you are calling whatever the interface points to and never truly call the function yourself. As long as the interface retains the original function name your code will not be broken - but underneath it all you are really calling a different function or an update version of one. Kinda confusing because I explained it poorly but hope it helps.
Thank you very much. It is really helpful !!!!
Bichi
Pointer to Pointer is also used in virtual function implementation in C++.
Each class having virtual function implements a virtual table that contains pointers to virtual functions. Now this address of virtual table is stored in the begining of each instance of that class.
In short each instance of class is having a pointer to a virtual table which in turn pointer to virtual function
Chintan R Naik
When used as a function parameter, you can use p2 when you actually want to modify a pointer's value in the calling code.Code:#include <stdio.h> void foo(int *p1) { p1 += 2; printf("foo: p1 = %p (%d)\n", p1, *p1); } void bar(int **p2) { *p2 += 5; printf("bar: *p2 = %p (%d)\n", *p2, **p2); } int main(void) { int array[] = {1,2,3,4,5,6,7,8,9}, *a1 = &array[3]; printf("main: a1 = %p (%d)\n", a1, *a1); foo(a1); /* a1 remains the same */ printf("main: a1 = %p (%d)\n", a1, *a1); bar(&a1); /* a1 is changed */ printf("main: a1 = %p (%d)\n", a1, *a1); return 0; } /* my output main: a1 = 0012FF74 (4) foo: p1 = 0012FF7C (6) main: a1 = 0012FF74 (4) bar: *p2 = 0012FF88 (9) main: a1 = 0012FF88 (9) */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*