Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
}
like image 719
Austin Avatar asked Nov 13 '16 02:11

Austin


3 Answers

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.

like image 148
artm Avatar answered Sep 20 '22 21:09

artm


Arrays are allocated contiguous memory location ( all elements are stored contiguously), so A[i] ( the element present at ith index of the array) will be i memory units away from the base address of the array A.
Hence A[i] is equivalent to *( A + i ).

The pointer stores the address and not the contents within. So, the local variable ceases to exist outside the function ( local scope), thereby giving different results outside the function.

like image 31
Akash Mahapatra Avatar answered Sep 21 '22 21:09

Akash Mahapatra


does using index brackets for a pointer also dereference it?

yes, it does. ptr[i] is equivalent to *(ptr + i).

It is undefined behavior to access the out of scope local variable num. Essentially p is pointing to a local variable num. After returning from fn(), num goes out of scope, so anything can be stored at its address.

like image 41
Saurav Sahu Avatar answered Sep 20 '22 21:09

Saurav Sahu