user133466
user133466

Reputation: 3415

pointers in C programming

int main(void) {
  int x = 0;
  char* p = (char*) &x;
  int k = 0;
  while (x != -1) {
    *p = -1;
    p = p + 1;
    k = k + 1;
  }
  printf("%d", k);
}

We have already set p to the address of x with char* p = &x; logically, *p=-1 should have replaced the value of x on the first iteration (k=1). In reality (or when I ran the code in VS), it took 4 iterations to complete the value assignment. Why? and since *p = -1 is executed in every iteration, where did the other three -1s go? Thanks

Upvotes: -1

Views: 282

Answers (5)

ian
ian

Reputation: 1685

The address of x initially contains these values:

Byte   1st 2nd 3rd 4th
Value  255 255 255 255

First iteration:
*p = -1; -> Address of x 255 255 255 255
p = p + 1; -> points p to 2nd byte

Second iteration:
*p = -1; -> Address of x 255 255 255 255
p = p + 1; -> points p to 3rd byte

Third iteration:
*p = -1; -> Address of x 255 255 255 255
p = p + 1; -> points p to 4th byte

4th iteration:
*p = -1; -> Address of x 255 255 255 255
p = p + 1; -> points p to 5th byte(outside of x's address)

From 5th and so forth the value of x will still be -1. I think your program stopped at forth iteration because on the 5th iteration pointer p is already out of bounds. Also, compiler should have given you a warning at compile time because you did not typecast the address of x when assigning it to p. It should have been:
char* p = (char*) &x;

Upvotes: 1

Zan Lynx
Zan Lynx

Reputation: 54363

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.

Upvotes: 2

Arthur Reutenauer
Arthur Reutenauer

Reputation: 2630

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

Upvotes: 1

Keith Randall
Keith Randall

Reputation: 23265

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.

Upvotes: 7

SteveC
SteveC

Reputation: 19

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

Upvotes: 1

Related Questions