Illegal Arithmetic operation on Pointer in C++ language
In pointer arithmetic only pointer subtraction is possible and other operation link addition, multiplication, divide and modulus are not possible. i.e
Address1 + Address2 = Illegal
Address1 * Address2 = Illegal
Address1 / Address2 = Illegal
Address1 % Address2 = Illegal
Address1 - Address1 = (simple subtraction of two address) / Size of datatype which pointer points.
Write a program which demonstrate the arithmetic operation on pointer.
a. program which demonstrate the subtraction operation on pointer
#include<iostream>
using namespace std;
int main()
{
int x=10, y=20;
int *ptr1 = &x;
int *ptr2 = &y;
cout<<"Difference between ptr2 and ptr1 is :"<< ptr2-ptr1;
return 0;
}
}
The above program output is tested on www.jdoodle.com
Output:
Address of ptr1 is :0x7ffd55431770
Address of ptr2 is :0x7ffd55431774
Difference between ptr2 and ptr1 is :1
b. program which demonstrate the addition operation on pointer
#include<iostream>
using namespace std;
int main()
{
int x=10, y=20;
int *ptr1 = &x;
int *ptr2 = &y;
cout<<"Difference between ptr2 and ptr1 is :"<< ptr2+ptr1;
return 0;
}
}
The program output is tested on www.jdoodle.com
Output:
jdoodle.cpp: In function 'int main()':
jdoodle.cpp:12:54: error: invalid operands of types 'int*' and 'int*' to binary 'operator+'
cout<<"Difference between ptr2 and ptr1 is :"<< ptr2+ptr1;
c. program which demonstrate the multiplication operation on pointer
#include<iostream>
using namespace std;
int main()
{
int x=10, y=20;
int *ptr1 = &x;
int *ptr2 = &y;
cout<<"Difference between ptr2 and ptr1 is :"<< ptr2*ptr1;
return 0;
}
}
The program output is tested on www.jdoodle.com
Output:
jdoodle.cpp: In function 'int main()':
jdoodle.cpp:12:54: error: invalid operands of types 'int*' and 'int*' to binary 'operator*'
cout<<"Difference between ptr2 and ptr1 is :"<< ptr2*ptr1;
Thanks
Mukesh Rajput
Post A Comment:
0 comments: