Some C++ program which perform the pointer operations in C++ language:

Note: If you subtract two pointers result will be a number but number will not be a simple mathematical subtraction of two addresses but it follow some rules:

If two pointers are of same type then:


Address2 - Address1 = (simple subtraction of two address) / Size of datatype which pointer points.

1. Write a program which perform the difference operation on pointer variables.

#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 pointer is incremented with memory size 8 byte (4 for each int)
ptr = ptr + 2;
cout<<" Address of temp is : "<< temp;
cout<<endl;
cout<<" Address of pointer is : "<< ptr;
cout<<endl;
cout<<" Difference : "<< ptr - temp;
cout<<endl;
return 0;
}

Explanation: Here two pointer ptr and temp are of same type and both are pointing to int datatype variable.
ptr-temp = (0x7fff6ecf0bcc - 0x7fff6ecf0bc4 ) sizeof(int)
                  = 8/4 
                  = 2.

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


Output:

Address of temp is : 0x7fff6ecf0bc4
Address of pointer is : 0x7fff6ecf0bcc

Difference between ptr and temp : 2

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: