does using index brackets for a pointer also dereference it?
Correct, pointer arithmetic is equivalent to array index. p[index]
is the same as *(p+index)
.
Why does printing the 0th index of this pointer twice end up printing two different things?
Because you are using p
to point to a local variable (num
) whose scope ends when the fn()
function ends. What you observed is undefined behavior. Returning a pointer to local variable is bad practice and must be avoided.
Btw, just to see the scope effect, if you move the definition of the num
array to outside the fn()
function, then you will see consistent cout
behavior.
Alternatively, as @Marc.2377 suggested, to avoid global variables (which is bad practice), you can allocate the variable in the heap (int* num = new int[1];
). It would then be ok to return pointer p
from fn()
, but DON'T forget to call delete[] p
in main()
afterwards.