'why is the output 1 in this case and when i am doing t-p then its giving me -1
As you can see it is giving me 1 but why? When i do t-p then it gives me -1 . Why ?
int f=4, o=8;
int *p, *t;
p = &f;
t = &o;
printf("Difference between the two pointer is %d\n",p-t);
Solution 1:[1]
p-t
is not well-defined behavior. You cannot do pointer arithmetic unless the pointers point at the same array. Any kind of result is possible.
Furthermore the result of subtracting two pointers is a large integer type called ptrdiff_t
. To print that one with printf
you need to use %tu
.
Although it is quite possible that the two variables are allocated adjacently in memory with 1 sizeof(int)
bytes in between. Do this instead:
#include <stdint.h>
printf("%llu\n", (uintptr_t)p);
printf("%llu\n", (uintptr_t)t);
On a gcc x86 Linux PC I get:
140720377482824
140720377482828
So the result -1
or 1
aren't very strange despite invoking undefined behavior.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lundin |