What is the meaning of "array is not a pointer and pointer is not an array BUT an array decays to a pointer"?
Also, I know that for an array int A[2][3]; A on its own is a pointer i.e it contains an address and A[1] is also a pointer, it also contains an address to the first element of A[1]. A[1][0] is an int and not a pointer.
This means that A and A[1] must be stored in different location in memory than A[1][0] which is an int. However, when I print the addresses using cout << &A; cout<< &A[0] and cout << &A[0][0], they are ALL the same! HOW COME!?!?!?
> What is the meaning of "array is not a pointer and pointer is not an array BUT an array decays to a pointer"?
It means that:
a. There is an implicit conversion from array of T to (a pure rvalue of type) pointer to T
b. The array-to-pointer conversion has the highest conversion rank - an exact match.
Array-to-pointer decay
There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are.
OK, that is clear; and what about the second part of the question that for an array A[2][3] how can the address of A be the same as address of A[0] which is same as address of A[0][0]? If I create an array using dynamic memory allocation of the same size, I do not get the same effect.
> I know that for an array int A[2][3]; A on its own is a pointer i.e it contains an address
A on its own is an array; it does not contain an address.
(The result of the array-to-pointer conversion is a prvalue - ie., an anonymous temporary.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int main()
{
using a3 = int[3] ; // array of 3 int
using a2_3 = a3[2] ; // array of two 'array of 3 int'
using a2_3 = int[2][3] ; // same as above
a2_3 A ; // same as int A[2][3]
a3* pa3 = A ; // array-to-pointer conversion: pa3 is pointer to 'array of 3 int'
std::cout << "pa3: " << pa3 << " address of pa3: " << &pa3 << '\n' ;
int* pi = A[0] ; // array-to-pointer conversion: pi is pointer to int
std::cout << " pi: " << pi << " address of pi: " << &pi << '\n' ;
}
----------------------------------------------------------------------
| | |
| A[0] | A[1] |
| | |
----------------------------------------------------------------------
^
|
pa3: A decays to pointer to its first element (pointer to int[3] 'array of 3 int')
----------------------------------------------------------------------
| . . | |
| A[0][0] . A[0][1] . A[0][2] | A[1] |
| . . | |
----------------------------------------------------------------------
^
|
pi: A[0] decays to pointer to first element of A[0] (pointer to int)