Arithmetic Operation with Pointer in C++ language

The different arithmetic operations which can be performed with pointers are given below:

1. Addition operation with pointers in C++:

If we will add or subtract a number from an address the result will also be an address. For example, Address + number = New_ Address  
Address - number = New_Address 
Address++ = New_Address 
Address-- = New_Address
++Address = New_Address 
--Address = New_Address. 

Here the New_Address = Address + number * Size of Datatype which pointer is pointing

Programming Example related to Pointer addition:

1. Write a C++ program which operate Arithmetic operators with pointer.

#include<iostream>
using namespace std;
int main()
{
int x=10;
int *ptr = &x;
cout<<"First time the address of pointer is : "<< ptr;
cout<<endl;
// Here we increment the pointer with 1, means poinetr is incremented with memory size 4 byte (for int)

ptr = ptr + 1; 
cout<<" Address of pointer after one integer increment : "<< ptr;
cout<<endl;
// Here again we increment the pointer with 1, means poinetr is incremented with memory size 4 byte (for int)
ptr = ptr + 1;
cout<<" Address of pointer after one integer increment again : "<<ptr;
return 0;
}

The output of this program is tested on www.jdoodle.com

Note: The output of the above program which is given below varies computer to computer, because every computer has their own memory location. 

Output:
First time the address of pointer is : 0x7ffe2ad12fdc
Address of pointer after one integer increment : 0x7ffe2ad12fe0
Address of pointer after one integer increment again : 0x7ffe2ad12fe4


2. Addition operation on pointer in C++:

#include<iostream>
using namespace std;
int main()
{
int x=10;
int *ptr = &x;
int *temp;
temp = ptr;
// Here we increment the pointer with 1, means poinetr is incremented with memory size 4 byte (for int)
ptr = ptr + 1;
cout<<" Address of pointer is : "<< ptr;
cout<<endl;
cout<<" Address stored in temp pointer is : "<< &temp;
cout<<endl;
return 0;
}

Note: In the above program the value stored in the temp varies as the address of the ptr varies. Here, line code " temp = ptr;" store the ptr value in temp. In the next line " ptr = ptr + 1;" change the value of ptr to one ( int). The change in ptr automatically change the value of temp also. The output of the above program which is given below varies computer to computer, because every computer has their own memory location.

The output of this program is tested on www.jdoodle.com


Output:
Address of pointer is : 0x7fff0a016c58
Address stored in temp pointer is : 0x7fff0a016c58


Thanks
Mukesh Rajput

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: