C++ Pointer Operator
In this chapter we are going to study C++ Pointer Operators. C++ provides two pointer operators one is value at operator or indirection operator and address operator.
C++ Pointer Operator
C++ Address of
Operator (&)
- The & is a unary operator means it requires only one operand.
- The
Address of
Operator returns the memory address of its operand. Address of
operator has the same precedence and right-to-left associativity as that of other unary operators.- Symbol for the bitwise AND and the
address of
operator are the same but they don’t have any connection between them
C++ Program : Address of Operator
#include<iostream> using namespace std; int main() { int num=10; cout << "Value of number : " << num << endl; cout << "Address of number : " << &num << endl; }
Output :
Value of number : 10 Address of number : 0xffad72dc
Summary
Point | Explanation |
---|---|
Operator | Address of |
Type | Unary Operator |
Operates on | Single Operand |
Returns | Address of the operand |
Associativity | right-to-left |
Explanation | Address of operator gives the computer's internal location of the variable. |
C++ Indirection
Operator *
- The Indirection operator * is a unary operator means it requires only one operand.
- Indirection Operator (*) is the complement of
Address of
Operator (&). - Indirection Operator returns the value of the variable located at the address specified by its operand.
C++ Program : Indirection Operator
#include<iostream> using namespace std; int main() { int num=10; int *ptr; ptr=# cout << " num = " << num << endl; cout << " &num = " << &num << endl; cout << " ptr = " << ptr << endl; cout<< " *ptr = " << *ptr << endl; }
Output :
num = 10 # = 0xffcc2bd8 ptr = 0xffcc2bd8 *ptr = 10
Calculations:
// Sample Code for Dereferencing of Pointer *(ptr) = value at (ptr) = value at (0xffcc2bd8) = 10 //Address in ptr is nothing but address of num
Summary
Point | Explanation |
---|---|
Operator | Indirection Operator |
Type | Unary Operator |
Operates on | Single Operand |
Returns | Value at address of the operand) |
Associativity | right-to-left |
Though multiplication symbol and the “Indirection Operator” symbol are the same still they don’t have any relationship between each other.
Both & and * have a higher precedence than all other arithmetic operators except the unary minus/plus, with which they share equal precedence.