Search code examples
c++arraysmultidimensional-arraypointer-arithmetic

Pointer arithmetic with multidimensional Array Notation


This is my first question :)

double MyArray[][6];
double* Myptr = MyArray[0];

So i've been wondering why, in pointer Arithmetic, I can notate a pointer to move in a single dimension like this,

*(Myptr + i);

but if i try to move through the dimensions of the array using a for loop it won't let me

*(*(Myptr + i) + j); 

However it does let me use this notation with the array itself.

*(*(MyArray + i) + j);

I wanted to know why is this a restriction? or maybe i am writing it down incorrectly.


Solution

  • Myptr is a pointer to double, so *(Myptr + i) is a double, and while you can add j to that, you cannot dereference the result.

    Had you declared Myptr like this:

    double (*Myptr)[6] = MyArray;
    

    then Myptr would be a pointer to an array of 6 doubles. Consequently *(Myptr + i) would be a double[6], and the expression would work.

    That you can index arrays using this syntax is unfortunately surprising to people who see it the first time and have never been taught about pointer decay. A funny thing about arrays in C and C++ is that they decay into pointers in almost all circumstances. What this means is that very nearly always when you use an array (exceptions exist), the array is implicitly converted to a pointer to its first element and the rest is done with pointer arithmetic.

    For example, this is the case when you write MyArray[i]. The standard defines MyArray[i] to mean *(MyArray + i) (the standard uses more parentheses, but this is what it boils down to), which makes sense when you understand that MyArray decays to a pointer, i is added to this pointer, and the resulting pointer is dereferenced. It also explains why i[MyArray] is equally valid (if in bad style).

    In the context of multidimensional arrays, it is important to understand that a multidimensional array is merely an array of arrays. MyArray is, in your case, an array of arrays of doubles. MyArray[0] is, then, an array of doubles. In pointer decay, MyArray decays to a pointer to array of doubles, and when you dereference that pointer and work with the array it points to, then that array also decays to a pointer (to double) when you work with it. It's decay all the way down.