To have a look from a slightly different angle, about the binary +
operator, chapter 6.5.6, paragraph 8 of C99
standard says, [emphasis mine]
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and
(P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist.
So, in your First case, p
is of type char *
and (p + 1)
gives a result as a pointer which is incremented by sizeof(char)
[that's 1 byte, most of the cases] and hence points to the 2nd element of the char array held by p
. Since actually, the array held by p
is of type int
[Let's say 4 bytes of length, in a 32 bit system], so as per the value stored, [1
getting stored as 0000 0000 0000 0001
], the *(p+1)
prints out 0
.
OTOH, in your second case, p
is of type int *
and (p + 1)
gives a result as a pointer which is incremented by sizeof(int)
and hence points to the 2nd element of the int array held by p
. Since actually, the array held by p
is of type int
, so as per the value stored, [int x[] = {1, 2, 3};
], the *(p+1)
prints out 2
.