Reputation: 113
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.
Upvotes: 0
Views: 112
Reputation: 2433
*A, or A[0], is itself an array of 10 elements and and array is always expressed by a pointer to its first element. However A[10][10] (let's say an array of ints) is effectively a block of memory holding 100 ints, the 10 of the first row followed by the 10 of the second row and so on. But if the expression *A or A[0] would return an int instead of a ptr to that row, it would be impossible to use the expression A[0][0], right ?
However, because such multidimensional array is a single block of memory, it's also possible to cast it to a pointer and then access it with an expression of this kind :
((int *)A)[iRow * 10 + iCol];
Which is equivalent to the expression :
A[iRow][iCol];
But this if it's possible for a 2D array declared this way :
int main()
{
int A[10][10] = { 0 };
A[9][9] = 9999;
printf("==> %d\n", ((int *)A)[9 * 10 + 9]); //==> 9999
return 0;
}
It is not if the memory is potentially made of separate blocks of bytes (probably requiring several calls to malloc) as with this kind of expressions :
int * A[10]; // or
int ** A;
Upvotes: 1
Reputation: 224052
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]
.Upvotes: 1
Reputation: 67979
A decays to a constant pointer to the first element of the array A[0][0]
No, it does not. Why?
C standard specifies that *(pointer + integer) == pointer[integer]
so the *A
is an equivalent of *(A + 0)
which is A[0]
. A[0]
will not give you the element A[0][0]
only the single dimensional array which will decay to pointer to the first element of the first row of this array.
Upvotes: 0