The output you see is because you assigned the address 0x02
to the pointer j
when you write j + 1
you are incrementing it by 1
is the same as incrementing it's address by sizeof(int)
or sizeof(*j)
which is the same.
But the behavior is actually undefined as was commented here originally by @Filipe Gonçalves, and replied to my question - here by @Kninnug
C11 §6.5.6/8:
[..] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. [..]
you can check the official document to read more about it.
Also, your printf()
calls are cause of undefined behavior. You should print pointers with the %p
specifier and cast the pointer to void *
, and if you want the assignment to be correct you should also cast the address to int *
in order for it to work.
Casting the i
to (int *)
might also be insufficient if your system is 64 bits.
The line
j = i;
could cause undefined behavior if you ever dereference j
.
You should not assign an integer to a pointer that way, perhaps you meant
j = &i;
otherwise with compilation warnings enabled, the compiler should warn you about the incorrect assignment, though it's valid it's not correct.
Note: main()
returns int
, and you have declared/defined it as not returning a value.