I read different things on the Internet and got confused, because every website says different things.
I read about *
referencing operator and &
dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to. So I got confused.
Can I get a simple but thorough explanation about "referencing and dereferencing"?
Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:
int c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1
Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the memory address that is pointed by the pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.
int n1;
n1 = *p1;
Invalid dereferencing may or may not cause crashes:
Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.
References:
http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators
& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.
http://www.cplusplus.com/doc/tutorial/pointers/
& is the reference operator
* is the dereference operator
http://en.wikipedia.org/wiki/Dereference_operator
The dereference operator * is also called the indirection operator.