I am not very clear about the pointer in C++, would anyone let me know
the difference of the following usage of pointer.
Sure
int* a
int *a
Same exact thing. Should it be on a, or on int? It doensn't change a thing
as far as the compiler is concerned and for clarity there are arguments on
both sides. The important thing to know is that "int *a, b;" will declare a
int pointer (a) and an integer (b), rather than two pointers...
As for what a pointer is, it's simply a placeholder for an address...
Ex:
int v= 12;
int *a= &v;
int *b= &v
int *c= &v;
*a= 13;
// At this point, v == 13, *a == 13, *b == 13 and *c == 13
Again, both are the same. They are NOT pointers though they are references.
A reference is similar to a pointer, but it's actually just a variable that
shares the same address as the object it's initialized with. It makes their
use easier for the non initiated, I guess, but it lacks the possibility of
being set to nothing (NULL).
Ex:
int v= 12;
int &a= v;
int &b= v;
int &c= v;
a= 13;
// At this point, v == 13, a == 13, b == 13 and c == 13
That would be a reference to a pointer...
Ex:
int v= 12;
int &r= v;
int *p= &r;
int *&rp= p;
*rp= 13;
// At this point, v == 13, r == 13, *p == 13, **rp == 13
In my opinion references should be avoided unless necessary. I mostly do C
with occasionnal C++ and I can count on the fingers of one hand the times I
had to use references in the past 5 years...
Alex.