Given this code:
int *p, *q;
p = (int *) 1000;
q = (int *) 2000;
What is q - p
and how?
It's actually undefined, according to the standard. Pointer arithmetic is not guaranteed to work unless the pointers are both pointing to either an element in, or just beyond, the same array.
The relevant section of the standard is 6.5.6:9 (n1362 draft of c1x but this hasn't changed since c99) which states:
When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.
You'll most likely get 250 if your int
datatype is 4 bytes but there's no guarantee. Undefined behaviour (unlike implementation-defined behaviour) means just that, undefined. Anything can happen, up to an including the total destruction of a large proportion of space-time.
A refresher course:
q - p is 250.
2000 - 1000 = 1000
1000 / sizeof(int) = 250
pointer arithmetic, assuming sizeof(int) is 4.
struct foo { int ar[1000]; } big[10];
char small[10];
struct foo *fs, *fe;
char *ss, *se;
fs = &big[0]; fe = &big[9];
ss = &small[0]; se = &small[9];
fe - fs == se - ss;
That is, the difference between the two pointers in this case is the number of array elements between them. In this case it is 0, 1, ... 8 or 9 elements.
q-p
supposed to return how many steps with increment you should do to go from p
to q
. Which is 1000 / sizeof(int)
and equals 250. Remember q++
will actually go to the next element of type int, not in the middle of it, so it should add 4 to the actual value of the pointer. Hence the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With