char

plz explain the output

1
2
3
4
5
6
7
8
#include <stdio.h>
int main(){
int i =300;
char *ptr = (char*)&i;
*++ptr=2;
printf("%d",i);
}
Last edited on

You initially set 'i' to 300, which in memory is 2c01. You assign the memory address of 'i' to your pointer 'ptr'. Then increment the pointer 'ptr' by 1 and assign 2 to the next memory address. The memory address for 'i' then contains 2c02.

300 is 0x12c
556 is 0x22c
but how does the value of i change?
The value of i is held at an address in memory, you created a pointer to that same memory address and then changed the contents of that address.
Last edited on
Topic archived. No new replies allowed.