I have a program question, here is the code.
int main()
{
int *p,*q;
p=(int*)1000;
printf(\"%d \",p);
q=(int*)2000;
printf(\"%d\",q);
printf(\"%d\",(p-q));
retu
p
is a pointer variable, which can store only address of a int
variable. But you are storing 1000
as an address, which is invalid. And then you are storing 2000
to the variable q
.
Now you are doing pointer arithmatic p-q
. Always pointer arithmatic will gives the output based on the size of the type of address. Which will work like (p - q)/sizeof(type)
.
Consider if p
and q
are char *
variable, then p-q
will gives you the output as -1000
In your case p
and q
are int *
variable, then p-q
will gives you the output as 250
if size of int
is 4 bytes. Execute this on the compiler where size of int
is 2 bytes, you will get a result as -500
.