Debug Pointer Arithmetic
I am unable to resolve why am I finding difference when I print the difference between the address of variable
Here is the code :
int main()
{
int *a,b = 5,e = 0;
int *c,d = 10,f = 0;
long t1,t2;
a = &b;
c = &d;
e = &b;
f = &d;
t1 = e - f;
t2 = a - c;
printf("\n Address of b using a: %x \t %d using e : %x \t %d value of b : %d",a,a,e,e,b);
printf("\n Address of d using c: %x \t %d using f : %x \t %d value of d : %d",c,c,f,f,d);
printf("\n Value of t1 : %d",t1);
printf("\n Value of t2 : %d \n",t2);
}
And here is the output :
Address of b using a: bf9e9384 -1080126588 using e : bf9e9384 -1080126588 value of b: 5
Address of d using c: bf9e9380 -1080126592 using f : bf9e9380 -1080126592 value of d: 10
**Value of t1 : 4
Value of t2 : 1**
Why is there开发者_JS百科 a difference between t1 and t2 when theyare assigned to the similar difference
Please let me know .
a
and c
are pointers, so taking the difference of pointers returns the number of elements in between them. e
and f
are integers (whose values are simply the addresses of b
and d
); taking the difference of integers is literally just a subtraction, so it returns the number of bytes.
Note (1): The behaviour that results from taking the difference of two pointers that don't point to elements of the same array is undefined.
Note (2): The behaviour that results from assigning an address to an int
is implementation-defined.
Note (3): The difference of two pointers is of type ptrdiff_t
, whose size is implementation-defined. Therefore, assigning this to a long
is also implementation-defined.
Note (4): It's considered pretty bad practice to mix the declarations of pointers and non-pointers on the same line (e.g. int *a,b = 5,e = 0;
), as it's incredibly confusing!
The reason you are seeing different values is that e-f
is int
arithmetics, whereas a-c
is int*
arithmetics. In int*
arithmetics, the difference is the number of ints
that could be placed between the two pointers, so the result is 4 times less with 4-byte ints.
This said, subtracting two pointers that do not point inside the same array is called "undefined behavior" and in theory anything could happen.
精彩评论