tags:

views:

134

answers:

5
+1  A: 

Because (on your machine) an int is four bytes, but a char is 1.

SteveC
+6  A: 

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.

Keith Randall
That's probably why he has the (char*) cast in there, to silence the warning. C always lets you shoot your feet off.
Zan Lynx
Yeah, that cast appeared after I wrote my answer :)
Keith Randall
+1  A: 

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...

Arthur Reutenauer
+2  A: 

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.

Zan Lynx
+1  A: 
ian