The program has undefined behavior because of lines 7, 9, 10, and 11. In other words, it can do
anything.
If we assume that the program actually does what the programmer thought it would do, it's because of pointer arithmetic. Casting an 'int *' to a 'char *' "converts" (so to speak) the pointed-to array to an array of chars. In memory, the int array looks like this (separated by bytes):
02 00 00 00 03 00 00 00 04 00 00 00
The expression p+1 evaluates to a pointer that is 1 char in front of p. So the old p pointed to the char 02, and the new one points to the 00 next to it.
Lines 9 and 11 are particularly nasty. Dereferencing a pointer of one type as a pointer of another type at least has (if you do it right) no chance of smashing the stack.
With the way printf() works internally (with variadic functions), telling printf() that you're passing an int (with "%d") and then passing something else entirely can wreak havoc in the stack and your program can end up executing data as if it was code, leading to very bad things.
If you ever need to print a char as if it was an int, make an explicit cast:
1 2
|
//char c;
printf("%d", (int)c);
|
I bet whoever wrote this thought they were being pretty clever, and not showcasing their own ignorance of C.