it's a pointer arithematic question
//code
#include<iostream>
using namespace std;
int main()
{
int a=20,b=50,*p,*q;
p=&a;
q=&b;
int c=p-q;
cout<<c; //Here I'm getting 1 for all positive value of 'a' and 'b'
return 0;
}
i tried long int c also
You substracting the values of the pointers
p
andq
itself - actually the addresses ofa
andb
in memory and assign the result to theint
c
.If you want to substract the value
20
(a
) by50
(b
), you need to dereference the pointersp
andq
by the*
operator to obtain the values of the objects they point to.Use
int c = *p - *q;
instead.If you want to substract the values of the pointers itself, there are to points to consider:
An
int
is in most cases not capable to hold the number of a memory location. Assigning an number above the range of anint
invokes undefined behavior. To store the number of the memory address, you need at least along int
.The substraction is made by the pointer types itself. Thus, the result of
1
.You need to define
c
as of typelong int
and cast both pointers tolong int
:Output:
Note that both objects
a
andb
do not need to be stored subsequent in memory.sizeof(int)
is not always 4, although it is common for most modern implementations.