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!~
Printable View
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.
* is basically the deferencing operator.
& is the address of operator.
& is also used to declare reference variables.
* is used to declare a pointer type variable.
int *p=&i;//p is pointing to the location of i.
to modify value of i, *p is used to derefer to i.
separate memory is allocated for a pointer type variable (usually 2 bytes).
int &p=i;
p is referring to location of i.p is used in the same manner as i.
no separate memory is allocated.
hope it clears the mist.
cr
Thx u guys!
can we do
cout << i;
I asked this question because I think &p refers to the address.
Thank you.
jeez you must have a well old 16-bit system. Pointers are 4 bytes on a 32bit system.Quote:
separate memory is allocated for a pointer type variable (usually 2 bytes).