Wednesday, November 9, 2016

Pointer Arithmetic

Tags

Pointer Arithmetic involves the following operations
1.Increment / Decrement pointer
2.Addition  / Subtraction of integer
3.Subtraction of Two Pointers

Following Program Illustrates the Concept:

#include<iostream>
using namespace std;
main()
{
int a[3]={1,2,3};
int *p,*q;
p=&a[0];
q=&a[2];
//incrementing decrementing
cout<<"Value"<<"\t"<<"Address"<<"\n";
cout<<*p<<"\t"<<p<<"\n";
p++;
cout<<*p<<"\t"<<p<<"\n";
p--;
cout<<*p<<"\t"<<p<<"\n";
// addition and subtraction of integer
p+=2;
cout<<*p<<"\t"<<p<<"\n";
p-=2;
cout<<*p<<"\t"<<p<<"\n";
//subtaction of two pointers
cout<<"q-p= ";
cout<<q-p;
}

Output: