C++ Pointer Operators (& and *)
C++ provides two pointer operators: the address-of operator & and the indirection operator *.
A pointer is a variable that contains the address of another variable. You can say that a variable that contains the address of another variable "points to" that other variable. The variable can be of any data type, including objects, structures, or pointers.
Address-of operator &
& is a unary operator that returns the memory address of its operand. For example, if var is an integer variable, then &var is its address. This operator has the same precedence as other unary operators, and it is evaluated from right to left.
You can read the & operator asAddress-of operator, this means that,&varread as "the address of var".
Indirection operator *
The second operator is the indirection operator *, which is the complement of the & operator. * is a unary operator that returns the value of the variable at the address specified by its operand.
Please see the following example to understand the usage of these two operators.
Example
using namespace std;
int main ()
{
int var;
int *ptr;
int val;
var = 3000;
// get the address of var
ptr = &var;
// Get the value of ptr
val = *ptr;
cout << "Value of var :" << var << endl;
cout << "Value of ptr :" << ptr << endl;
cout << "Value of val :" << val << endl;
return 0;
}
When the above code is compiled and executed, it produces the following results:
Value of var :3000 Value of ptr :0xbff64494 Value of val :3000other extensions