'&' and '*'
I'm always confusing with the '*' and '&' in C++. Would anyone mind telling me the differences before them? Does any website talk about '*' and '&'? Thank you!~
When defining a pointer we use *:
int * pI = NULL;
char* pC = NULL;
in the above case both pointers have been set to NULL or do not point to anything.
The & is reference to or address of, so below:
int i =0; //i = 0
char c = ' ';c = a space ' ';
pI = &i;
pC = &c;
we assign the address of i to pointer pI and the address of c to Pc. Now we can use the * to dereference our pointers, which is to get the value of the item they point to:
int t = *pI; this expression will resolve to setting t to 0 because pI points to i and i == 0.
*pI = 10; this expression will resolve to setting i to 10 because pI points to i.
char ch = *pC; this expression will resolve to to assigning ' ' (a space) to ch.
*pC = 'A'; this expression will resolve to setting c to 'A'.
now comes the wacky part of a & ( reference ). I can define a reference to i;
int &rI = i; //rI will always equal i and vice a versa
The reference (&) is like a constant pointer that is automathically dereferenced. It is usually used for function argument lists and function return values.
I hope that helps. For more info I would recommend reading "Thinking in C++ second edition" by Bruce Eckel.