S
Simon Biber
Morris said:main() (in (e-mail address removed)) said:
| 2) My second question is ,
|
| #include<stdio.h>
|
| int main(void)
| {
| int *p = (int*) 1;
| int *q = (int*) 2000;
| printf("%d\n",(q-1));
| printf("%d\n",(q-p));
| }
This code has undefined behaviour. The pointers do not point to valid
int objects. In addition, p is probably not aligned correctly for int.
Attempting to subtract 1 from q is undefined behaviour since q does not
point to a valid int object nor array of int nor allocated memory. The
same goes for subtracting p from q, but in addition the alignment issues
may cause problems.
Attempting to print a pointer to int through an int specifier in printf
is also undefined behaviour. Pointers and ints often have different
sizes, and may even be passed in different locations.
In practise though, you seem to have got results along the lines of
2000 - 1 * 4 == 1996
and
(2000 - 1) / 4 == 499
where 4 was sizeof(int) on your machine.
That should make it clear where the 499 came from.
| output:
| 1996
| 499
|
| I can understand why the first printf outputs 1996, (because when
| you decrement an integer pointer, it points to the prevoius
| integer which is four bytes offset from the current location)
| But i cannot understand why second printf outputs 499 ?
| Can anyone throw light on this one ?
My results were:
1999
1999
That may have been because you ran it on an unusual system where the
size of int is 1 byte. On such a system, a byte must be at least 16 bits
wide.