Search code examples
cpointersmultidimensional-arrayimplicit-conversionpointer-arithmetic

In 2D array A[m][n], how value of A is same as *A?


What I know about 2D array:

  1. In array the array name is pointer to first element's address
  2. Here we can think A as array of array, so A would point to 0th 1D array
  3. So A+i would point to ith element of A
  4. *(A+i) would point to first element of ith element of A
  5. Then in 2D array A+i address value should be same as *(A+i)

But this doesn't make sense to me how A value is same as of *A, can someone tell me how this is working in memory, I know it is correct but I can't explain it to myself


Solution

  • The statement

    In array the array name is pointer to first element's address

    is wrong.

    For any array, its symbol by itself will decay to a pointer to its first element.

    So for your array A it will decay to &A[0].

    If you dereference that pointer, as what happens with *A, then you have *(&A[0]). Which is the same as plain A[0].

    Since your array A is an array of arrays, then A[0] is an array, which will in turn also decay to a pointer to its first element. So A[0] will decay to &A[0][0].

    So *A will be the same as &A[0][0].

    There are however a big different in types for the different pointers.

    Take your example array:

    int A[3][4];
    

    Then &A[0] will be a pointer to an array of four int values, or int (*)[4]. And &A[0][0] will be a pointer to a single int value, or int *.


    Now to why all these pointers seems to be the same, it's because they are all pointing to the very same location, which also happens to be the same location as the array itself (i.e. &A, which will have the type int (*)[3][4]).

    If we "draw" it, it will look something like this:

    +---------+---------+---------+---------+---------+---------+-----+
    | A[0][0] | A[0][1] | A[0][2] | A[0][3] | A[1][0] | A[1][1] | ... |
    +---------+---------+---------+---------+---------+---------+-----+
    ^
    |
    &A
    |
    &A[0]
    |
    &A[0][0]
    

    As you can see, all three pointers will point to the same location, but as mentioned have different types.