Search code examples
cpointersmultidimensional-arrayindirection

Why application of indirection to a two-dimensional array gives a pointer?


After reading some posts on this site, I realized that array in C isn't just a constant pointer as I originaly thought, but is itself a distinct type, but in most cases array "decays" to a constant pointer to the first element of the array. Because of this new information, a question arised in my mind. Suppose we have a two-dimensional A[10][10]. Why is the result of the expression *A a pointer to the first element of the array ? I thought that in this expression, A decays to a constant pointer to the first element of the array A[0][0], and then the application of the indirection should give us the value of the A[0][0], but in fact it still gives us the address of the first element of the array. Certainly, something is wrong with my logic or my understanding of the arrays or pointers, so where do I get it wrong ?

Thanks in advance.


Solution

  • The first element of A is A[0], not A[0][0].

    This is because A is an array of ten things. C does not have two-dimensional arrays as a primary type. An array with multiple dimensions is derived or constructed as multiple layers of arrays. To the compiler, the resulting type is still just an array, whose elements happen to be further arrays.

    Thus, in *A:

    • A is converted to a pointer to its first element. That pointer is &A[0], so *A becomes *&A[0].
    • * and & cancel, so the expression becomes A[0].
    • A[0] is an array of ten elements, so it is converted to a pointer to its first element, &A[0][0].