Jake Jake - 18 days ago 5
C++ Question

Does using index brackets for a pointer dereference it?

Does using index brackets for a pointer also dereference it? And why does printing the 0th index of this pointer twice end up printing two different things?

#include <cstdlib>
#include <iostream>
#include <cstring>

using namespace std;

int *p;

void fn() {
int num[1];
num[0]=99;
p = num;
}

int main() {
fn();
cout << p[0] << " " << p[0];
}

Answer

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.

Comments