Why is the value of the pointer getting changed to 10(0xa) instead of incrementing the earlier address and assign 10 to that location?
To what location? There is no such location. p
was pointing to one int
, not an array of int
s. The pointer that results from such increment does not point to a location that you can perform indirection on. Attempting to do so as this code does has undefined behaviour, meaning absolutely anything can happen. The compiler is free to do whatever it pleases, because there are no requirements on what need to happen. Don't do it.
In your particular experiment, it appears that the two variables were located next to each other, and when incremented, the variable p
ended up pointing to itself, and then assigned 10, which is A in hexadecimal. There is no guarantee that this will happen again when you compile with a different compiler version or compiler options, or even if you make seemingly innocent changes to the code. Don't do it.