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);
}

Recommended Answers

All 3 Replies

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.

commented: Brilliant post.. +1

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.