Click here to Skip to main content
15,886,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <stdio.h>
    int main(){ 

int a=95;
int *ptrint=&a;
printf("%u\n",ptrint);
int  b=85;
int *ptri2=&b;

    printf("%u\n",ptri2);


printf("%u and %u\n",ptrint ,ptri2);
ptrint--;
printf("%u\n", ptri2 - ptrint ); //why its illegal 
printf("%u\n", ptrint -ptri2  ); // whys its legal 

return 0;

}


What I have tried:

As per logic say the way I am getting this error is because Its address not vairable . PLease do let me know if my logic is right here . I tried to subtract one address from another
Posted
Updated 4-Jun-22 9:57am

1 solution

Both are legal - if I run your code through an online C compiler (GDB) I get what I expect:
1396230176
1396230180
1396230176 and 1396230180
2
4294967294

The last number is an unsigned integer - it's actually -2 if you use a signed printf format code like "%d" instead of "%u"
However, pointer arithmetic is rarely of any real use, just like arithmetic performed on mobile phone numbers: you could subtract my number from yours and get a valid value, but it is not of any real use to anyone for anything!
 
Share this answer
 
Comments
Aayush Jain 2022 4-Jun-22 17:15pm    
printf("%u\n", ptrint -ptri2 ); // whys its legal still we are not getting its value
OriginalGriff 4-Jun-22 17:38pm    
You are getting it's value! It's just that the value is meaningless ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900