Jake Jake - 20 days ago 4
C++ Question

Index of a pointer

does using index brackets for a pointer also dereference it? 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

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 function ends. What you observed is undefined behaviour. Returning a pointer to local var is bad practice and must be avoided.

Btw, just to see the scope effect, if you move the definition of num array to outside function fn - then you will see consistent cout behaviour.

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 should be ok to return pointer p then in function fn - but DON'T forget to delete p in main() afterwards.

Comments