About the pointer in C
Consider the following programm,
#incl开发者_运维问答ude<stdio.h>
int main()
{
int marks[]={20,65,45,68,89};
int *x,*y;
x=&marks[2];
y=&marks[4];
printf("%p\n%p\n"x,y);
printf("%p\n%p\n",y-x,*y-*x);
return 0;
}
When I want to print out the value of y-x
, the console should give me a output equal to the difference between the addresses of the corresponding pointers. After all, we know that x
and y
are having addresses ('some integer value'). However it is not so. Why?
Pointer subtraction does not simply subtract the addresses but rather return the distance between two array elements (in terms of arary elements).
So y - x
is not a pointer but an integer of the value 2
- and to printf it, you shold use %d
formatting, now %p
.
If you print the differences using %p, you will probably get something that's a bit hard to read.
The proper way is probably to use %lu, and cast:
printf("%lu\n", (unsigned long) (y - x));
Printing the integer quantity *y - *x
as %p seems totally confused.
The result of subtraction of 2 pointers in the same array is the distance between those pointers in array, so y-x
should equal 2 in your example.
To get difference between addresses cast them to some integer before substracting:
printf("%d",(size_t)y-(size_t)x);
y-x
will evaluate to 2 - since the distance in between them is 2 ints.
If you print e.g. (char *) y - (char *) x
you will get the distance in characters
the console must give me a output equal to the difference between the addresses of the corresponding pointers
... and it does. For me, it outputs 2
. If you compare the addresses, you see that they are separated by 8 bytes, which is 2 int
s, which is the answer you sought.
精彩评论