C++ Address (&) and Indirection Operator (*)

- March 17, 2018
In this tutorial, you will know about address operator (&) and indirection (*) operator and their use with simple example programs. Someone may be confused that the * operator is a multiplication operator, but when * is used as unary operator, then it's considered as indirection operator.

What is Address Operator (&)

The address operator is a unary operator that is used to get memory address of a variable or object. This operator is also called reference operator and it's denoted by &.
Generally, address operator is used to get memory address of a variable and assign to pointer variable throw assignment statement. Such as:
      int x, *px;
      x = 155;
      px = &x;
In the above syntaxes, the value 155 is assigned to variable 'x'. Suppose, the memory address 1000 is allocated to variable 'x' and memory address 50000 is allocated to pointer variable 'px'. After executing the statement "px = &x" the contents of 'px' will be 1000. The presentation of this process is as follows:
pointing variable through cpp pointer

The pointer variable "px" is said to be pointing to variable "x".

What is Indirection Operator (*)

This operator is used with pointer variable to get the value of the variable whose memory address is stored in pointer variable. It is also unary operator that is denoted by *.
The use of * operator (with pointer variable) unable us to access data of a variable indirectly. This process is called de-reference the pointer. Therefore, the indirection operator is also known as de-reference operator.
For example, if we want to display the value of "x" indirectly by using pointer "px", the statement will be as:
(Suppose, Value of x = 20, Value of px = 15)
cout<<*px;
The above statement ↑ is equivalent to below statement ↓
cout<<x;
The indirection operator is also used to assign a value to a variable. For example, the following statement is assign a value 500 to variable "x" through this operator.
*px = 500;
The value 500 will be assigned to variable "x". We can also use interaction (*) operator to input value to a variable through keyboard during program execution. Such as, to input value to variable "x" through *px, the statement is:
cin>>*px;

Indirection and Address Operator Example Program

The following program assigns value to variables through pointer variables, computes the sum of values and displays result on the screen.
  #include<iostream>
  using namespcace std;
  main()
     {
      int a, b, *pa, *pb;
      pa = &a;
      pb = &b;
      *pa = 10;
      *pb = 15;
      cout<<"Sum of a and b = "<<a+b;
  return 0;
  }

Output of Program

Sum of a and b = 25