Following program gives me output 556 , I cant understand why ?

#include<stdio.h>
main(){
int i =300;
char*ptr =(char*)&i;
*++ptr = 2 ;
printf("\n%d",i);
}

Following program gives me output 556 , I cant understand why ?

#include<stdio.h>
main(){
int i =300;
char*ptr =(char*)&i;
*++ptr = 2 ;
printf("\n%d",i);
}

ptr points to the first byte of four that represent the integer 'i'

the bytes for 'i' are (44,1,0,0)

by taking the address of 'i' (&i) and casting it into a char pointer (char*), ptr only points to one byte. (44)

'*++ptr = 2' is taking the second byte (which is 1) and changing it to a 2... which makes the bytes for 'i' read (44,2,0,0) which = 556.

by putting the '++' before the pointer it increments the dereferenced bytes of 'i' rather than incrementing the memory address of ptr and then dereferencing it.

Comments
Brilliant post..

To add to my last post...

*++ptr = 2;

could also be written as...

*(ptr+1) = 2;

the problem with...

*ptr++ = 2;

is that '++' is an operator which permanently increments the address ptr points to, possibly making it point to something other than 'i'., and then changes the value at that new memory address to '2', which will cause access violation errors and cause things to crash.

Thank you very much Liinker.. Awesome example .. crystal clear..

This question has already been answered. Start a new discussion instead.