Because (on your machine) an int is four bytes, but a char is 1.
SteveC
2009-11-05 01:15:27
Replace char *p
with int *p
. Your assignment *p = -1
only writes 1 byte, and an int is 4 bytes.
Your compiler should have generated a warning, as your assignment char *p = &x
; is not type safe.
x
is an int but you declare p
as a char *
. On most modern architectures, an int will be exactly the length of 4 char's...
You are using a char size pointer to write into an int size memory space. The only reason it ever gets set to -1 is because of luck. -1 happens to be 0xff for a char and 0xffffffff for a int so after writing four 0xff you get one int sized -1.