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
pandqitself - actually the addresses ofaandbin memory and assign the result to theintc.If you want to substract the value
20(a) by50(b), you need to dereference the pointerspandqby 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
intis in most cases not capable to hold the number of a memory location. Assigning an number above the range of anintinvokes 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
cas of typelong intand cast both pointers tolong int:Output:
Note that both objects
aandbdo not need to be stored subsequent in memory.sizeof(int)is not always 4, although it is common for most modern implementations.