Home > Enterprise >  Why dereferencing is not required in pointer array?
Why dereferencing is not required in pointer array?

Time:10-31

In the code that is written below, when reading from cin, we should use the * operator before arr[i]. But without that, this code works perfectly. Why is that?

Similarly, we don't use * when we write to cout with pointer arrays. For instance, consider a multi-dimensional pointer array on the heap - cout << vararr[i][j] << endl; This also works.

int* variablesizedarr(int size){
    int* arr = new int [size];
    for(int i = 0;i < size; i  ){
        cin >> arr[i]; //shouldn't it be *arr[i] if the input is integers
    }
    return arr;
}

CodePudding user response:

we should use the * operator before arr[i]

No, that'd be an error.

From cppreference:

The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 E2)except evaluation order (since C 17), that is, the pointer operand (which may be a result of array-to-pointer conversion, and which must point to an element of some array or one past the end) is adjusted to point to another element of the same array, following the rules of pointer arithmetics, and is then dereferenced.

so operator[] takes care of dereferencing.

  • Related