C++ Pointer Arithmetic: This can be used to perform arithmetic operations on pointers. And there are totally four arithmetic operators present in C++ are ++, – -, + and -. The increment operator (++) will increment the value of the pointer according to the pointer’s type. While the address will be incremented by the size of the pointer’s type. So, the pointer will change its value and will store the address of the next element of the pointer’s type.
C++ Pointer Arithmetic
Increment a Pointer (++)
Example:
#include<iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; //let us have array address in a pointer. ptr = var; for(int i = 0; i < MAX; i++) { cout<<"Address of var[" << i << "] = "; cout<<ptr << endl; cout<<"Value of var[" << i << "] = "; cout<<*ptr << endl; //point to the next location ptr++; } return 0; }
Output:
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
Decrement a Pointer (- -)
Example:
#include<iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; //let us have the address of the last element in the pointer. ptr = &var[MAX-1]; for (int i = MAX; i > 0; i--) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; //point to the previous location ptr--; } return 0; }
Output:
Address of var[3] = 0xbfdb70f8
Value of var[3] = 200
Address of var[2] = 0xbfdb70f4
Value of var[2] = 100
Address of var[1] = 0xbfdb70f0
Value of var[1] = 10
Pointer Comparisons
The pointers may be compared by using the relational operators such as = =, <, and >.
Example:
#include<iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; //let us have the address of the first element in a pointer. ptr = var; int i = 0; while ( ptr <= &var[MAX - 1] ) { cout<< "Address of var[" << i << "] = "; cout<< ptr << endl; cout<< "Value of var[" << i << "] = "; cout<< *ptr << endl; //point to the previous location ptr++; i++; } return 0; }
Output:
Address of var[0] = 0xbfce42d0
Value of var[0] = 10
Address of var[1] = 0xbfce42d4
Value of var[1] = 100
Address of var[2] = 0xbfce42d8
Value of var[2] = 200