C++ allows pointers to perform the following arithmetic operations:
a. A pointer can be incremented (++) or decremented (--)
b. Any integer can be added or subtracted from a pointer.
c. One pointer can be subtracted from another.
For example:
int a[5], *p;
p = &a[0] OR p = a;
here, p refers to the base address (address of 1st element) of the array variable a.
We can increment pointer variable as follows:
p++; or ++ p; This statement moves the pointer to the next memory address. Similarly, we can decrement pointer variable as
p --; or -- p; this statement moves the pointer variable to the previous memory location.
Increment or decrement pointer variable depends on data type of pointer. if pointer variable is of type int then it increments or decrements by two positions in an array.
Program to illustrate pointer arithmetic:
#include<iostream.h>
#include<conio.h>
void main ()
{
int num[5]={56,75,22,18,90};
int *ptr, i; // Declration of pointer variable ptr
ptr=#
cout<<”array elements are::”;
for(i=0;i<5;i++)
{
cout<<*ptr << “\n”;
ptr=ptr+1;
}
ptr=num; // Initializing the base address to the ptr
cout<<”value of ptr:”<<*ptr; // Printing the value in the array
cout<<”\n”;
ptr++;
cout<<”value of ptr++:”<<*ptr;