Can anyone explain this program

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

not sure what kind of type casting will there be but a will be same i think because even if you do typecasting without getting error the address might not be the same as a’s address ,
so it should print 300 .

edit : just checked ,
char *b=(char *)&a;
and
char b = (char)a
doing the pretty much same task ,
only diff in 1st case b is ptr and 2nd case its char var .

int a=300; -> Storing 300 in variable a at a certain memory address
char *b=(char *)&a; - > b stores the address (memory location) of a
b++; -> incrementing the value of b i.e. the address got incremented. So b is now pointing to a new location

*b=1; -> Storing 1 to the new memory location pointed by b
printf("%d",a); -> Prints the value of a as 300 because no change was made to a

1 Like

Sorry, there was an mistake. Please now check it.